<commit_before># Copyright (C) 2010 Sebastian Wiesner <lunaryorn@googlemail.com>

# This library 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.

# This library 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 this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    udev
    ====

    A binding to ``libudev``.

    The central class is the :class:`Context`.  To use this library, create
    an instance of this class first.  Then use this class to list devices.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@googlemail.com>
"""

import sys
from collections import Mapping

import _udev

libudev = _udev.load_udev_library()

class Context(object):
    """
    The udev context.

    The context is the central object to access udev.  It represents the
    udev configuration and is required for all udev operations.

    The context is iterable, and returns a :class:`Enumerator` upon
    iteration.  This enumerator provides miscellaneous methods to filter the
    device tree.
    """

    def __init__(self):
        self._context = libudev.udev_new()

    def __del__(self):
        libudev.udev_unref(self._context)

    @property
    def sys_path(self):
        """
        The ``sysfs`` mount point as string, defaults to ``/sys'``.

        You can override the mount point using the environment variable
        :envvar:`SYSFS_PATH`.
        """
        return libudev.udev_get_sys_path(self._context).decode(
            sys.getfilesystemencoding())

    @property
    def dev_path(self):
        """
        The device directory path as string, defaults to ``/dev``.

        The actual value can be overridden in the udev configuration.
        """
        return libudev.udev_get_dev_path(self._context).decode(
            sys.getfilesystemencoding())

    def list_devices(self):
        """
        Return an :class:`Enumerator` to list devices.
        """
        return Enumerator(self)

def _assert_bytes(value):
    if not isinstance(value, str):
        value = value.encode(sys.getfilesystemencoding())
    return value

def _property_value_to_bytes(value):
    if isinstance(value, str):
        return value
    elif isinstance(value, unicode):
        return value.encode(sys.getfilesystemencoding())
    elif isinstance(value, int):
        return str(int(value))
    else:
        return str(value)

def _property_value_from_bytes(value):
    if value.isdigit():
        return int(value)
    else:
        return value.decode(sys.getfilesystemencoding())

def _check_call(func, *args):
    res = func(*args)
    if res != 0:
        raise EnvironmentError(
            '{0.__name__} returned error code {1}'.format(func, res))
    return res

class Enumerator(object):
    """
    An iterable over the list of devices.

    >>> context = Context()
    >>> devices = context.list_devices()

    Before iterating, the list can be filtered by different criteria:

    >>> devices = devices.match_subsystem('input').match_property(
    ...     'ID_INPUT_MOUSE', True)
    >>> for device in devices:
    ...     device.sys_name
    ...
    u'event7'
    u'mouse2'
    u'event4'
    u'mouse0'
    """

    def __init__(self, context):
        """
        Create a new enumerator with the given ``context`` (a
        :class:`Context` instance).

        While you can create objects of this class directly, this is not
        recommended.  You should call :func:`iter` on the ``context`` to
        retrieve an enumerator.
        """
        if not isinstance(context, Context):
            raise TypeError('Invalid context object')
        self.context = context
        self._enumerator = libudev.udev_enumerate_new(context._context)

    def __del__(self):
        libudev.udev_enumerate_unref(self._enumerator)

    def match_subsystem(self, subsystem):
        """
        Include all devices, which are part of the given ``subsystem``.
        """
        _check_call(libudev.udev_enumerate_add_match_subsystem,
                    self._enumerator, _assert_bytes(subsystem))
        return self

    def match_property(self, property, value):
        """
        Include all devices, whose ``property`` has the given ``value``.
        """
        _check_call(libudev.udev_enumerate_add_match_property,
                    self._enumerator, _assert_bytes(property),
                    _property_value_to_bytes(value))
        return self

    def __iter__(self):
        _check_call(libudev.udev_enumerate_scan_devices, self._enumerator)
        entry = libudev.udev_enumerate_get_list_entry(self._enumerator)
        while entry:
            yield Device.from_sys_path(
                self.context, libudev.udev_list_entry_get_name(entry))
            entry = libudev.udev_list_entry_get_next(entry)

class Device(Mapping):
    """
    A single device.

    This class subclasses the ``Mapping`` ABC, devices therefore support the
    dictionary protocol.  They map sysfs properties to the corresponding
    values:

    >>> context = Context
    >>> devices = context.list_devices().match_subsystem('input')
    >>> for device in devices:
    ...     if device.sys_name.startswith('event'):
    ...         device.sys_name, device.get('ID_INPUT_MOUSE')
    ...
    (u'event6', None)
    (u'event7', 1)
    (u'event3', None)
    (u'event4', 1)
    (u'event5', None)
    """

    @classmethod
    def from_sys_path(cls, context, sys_path):
        """
        Create a device from the given :class:`Context` and the given
        ``sys_path``.
        """
        if not isinstance(context, Context):
            raise TypeError('Invalid context object')
        device = libudev.udev_device_new_from_syspath(
            context._context, _assert_bytes(sys_path))
        return cls(context, device)

    def __init__(self, context, _device):
        self.context = context
        self._device = _device

    def __repr__(self):
        return 'Device({0.sys_path!r})'.format(self)

    @property
    def sys_path(self):
        """
        Absolute path of this device in ``sysfs`` including the mount point.
        """
        return libudev.udev_device_get_syspath(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def dev_path(self):
        """
        Kernel device path.

        Unlike :attr:`sys_path`, this path does not contain the mount point.
        However, the path is absolute and starts with a slash ``'/'``.
        """
        return libudev.udev_device_get_devpath(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def subsystem(self):
        """
        Name of the subsystem, this device is part of.
        """
        return libudev.udev_device_get_subsystem(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def sys_name(self):
        """
        Device name inside ``sysfs``.
        """
        return libudev.udev_device_get_sysname(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def dev_node(self):
        """
        Absolute path to the device node (including the device directory).
        """
        return libudev.udev_device_get_devnode(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def devlinks(self):
        entry = libudev.udev_device_get_devlinks_list_entry(self._device)
        while entry:
            yield libudev.udev_list_entry_get_name(entry).decode(
                sys.getfilesystemencoding())
            entry = libudev.udev_list_entry_get_next(entry)

    def __iter__(self):
        entry = libudev.udev_device_get_properties_list_entry(self._device)
        while entry:
            yield libudev.udev_list_entry_get_name(entry).decode(
                sys.getfilesystemencoding())
            entry = libudev.udev_list_entry_get_next(entry)

    def __len__(self):
        return len(list(self))

    def __getitem__(self, property):
        """
        Get a property from this device.
        """
        value = libudev.udev_device_get_property_value(
            self._device, _assert_bytes(property))
        if value is None:
            raise KeyError('No such property: {0}'.format(property))
        value = _property_value_from_bytes(value)
        if property == 'DEVLINKS':
            # special handle for device links list
            return value.split(' ')
        return value

    def __eq__(self, other):
        return self.dev_path == other.dev_path

    def __ne__(self, other):
        return self.dev_path != other.dev_path
<commit_msg>Docstring for Device.devlinks<commit_after># Copyright (C) 2010 Sebastian Wiesner <lunaryorn@googlemail.com>

# This library 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.

# This library 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 this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    udev
    ====

    A binding to ``libudev``.

    The central class is the :class:`Context`.  To use this library, create
    an instance of this class first.  Then use this class to list devices.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@googlemail.com>
"""

import sys
from collections import Mapping

import _udev

libudev = _udev.load_udev_library()

class Context(object):
    """
    The udev context.

    The context is the central object to access udev.  It represents the
    udev configuration and is required for all udev operations.

    The context is iterable, and returns a :class:`Enumerator` upon
    iteration.  This enumerator provides miscellaneous methods to filter the
    device tree.
    """

    def __init__(self):
        self._context = libudev.udev_new()

    def __del__(self):
        libudev.udev_unref(self._context)

    @property
    def sys_path(self):
        """
        The ``sysfs`` mount point as string, defaults to ``/sys'``.

        You can override the mount point using the environment variable
        :envvar:`SYSFS_PATH`.
        """
        return libudev.udev_get_sys_path(self._context).decode(
            sys.getfilesystemencoding())

    @property
    def dev_path(self):
        """
        The device directory path as string, defaults to ``/dev``.

        The actual value can be overridden in the udev configuration.
        """
        return libudev.udev_get_dev_path(self._context).decode(
            sys.getfilesystemencoding())

    def list_devices(self):
        """
        Return an :class:`Enumerator` to list devices.
        """
        return Enumerator(self)

def _assert_bytes(value):
    if not isinstance(value, str):
        value = value.encode(sys.getfilesystemencoding())
    return value

def _property_value_to_bytes(value):
    if isinstance(value, str):
        return value
    elif isinstance(value, unicode):
        return value.encode(sys.getfilesystemencoding())
    elif isinstance(value, int):
        return str(int(value))
    else:
        return str(value)

def _property_value_from_bytes(value):
    if value.isdigit():
        return int(value)
    else:
        return value.decode(sys.getfilesystemencoding())

def _check_call(func, *args):
    res = func(*args)
    if res != 0:
        raise EnvironmentError(
            '{0.__name__} returned error code {1}'.format(func, res))
    return res

class Enumerator(object):
    """
    An iterable over the list of devices.

    >>> context = Context()
    >>> devices = context.list_devices()

    Before iterating, the list can be filtered by different criteria:

    >>> devices = devices.match_subsystem('input').match_property(
    ...     'ID_INPUT_MOUSE', True)
    >>> for device in devices:
    ...     device.sys_name
    ...
    u'event7'
    u'mouse2'
    u'event4'
    u'mouse0'
    """

    def __init__(self, context):
        """
        Create a new enumerator with the given ``context`` (a
        :class:`Context` instance).

        While you can create objects of this class directly, this is not
        recommended.  You should call :func:`iter` on the ``context`` to
        retrieve an enumerator.
        """
        if not isinstance(context, Context):
            raise TypeError('Invalid context object')
        self.context = context
        self._enumerator = libudev.udev_enumerate_new(context._context)

    def __del__(self):
        libudev.udev_enumerate_unref(self._enumerator)

    def match_subsystem(self, subsystem):
        """
        Include all devices, which are part of the given ``subsystem``.
        """
        _check_call(libudev.udev_enumerate_add_match_subsystem,
                    self._enumerator, _assert_bytes(subsystem))
        return self

    def match_property(self, property, value):
        """
        Include all devices, whose ``property`` has the given ``value``.
        """
        _check_call(libudev.udev_enumerate_add_match_property,
                    self._enumerator, _assert_bytes(property),
                    _property_value_to_bytes(value))
        return self

    def __iter__(self):
        _check_call(libudev.udev_enumerate_scan_devices, self._enumerator)
        entry = libudev.udev_enumerate_get_list_entry(self._enumerator)
        while entry:
            yield Device.from_sys_path(
                self.context, libudev.udev_list_entry_get_name(entry))
            entry = libudev.udev_list_entry_get_next(entry)

class Device(Mapping):
    """
    A single device.

    This class subclasses the ``Mapping`` ABC, devices therefore support the
    dictionary protocol.  They map sysfs properties to the corresponding
    values:

    >>> context = Context
    >>> devices = context.list_devices().match_subsystem('input')
    >>> for device in devices:
    ...     if device.sys_name.startswith('event'):
    ...         device.sys_name, device.get('ID_INPUT_MOUSE')
    ...
    (u'event6', None)
    (u'event7', 1)
    (u'event3', None)
    (u'event4', 1)
    (u'event5', None)
    """

    @classmethod
    def from_sys_path(cls, context, sys_path):
        """
        Create a device from the given :class:`Context` and the given
        ``sys_path``.
        """
        if not isinstance(context, Context):
            raise TypeError('Invalid context object')
        device = libudev.udev_device_new_from_syspath(
            context._context, _assert_bytes(sys_path))
        return cls(context, device)

    def __init__(self, context, _device):
        self.context = context
        self._device = _device

    def __repr__(self):
        return 'Device({0.sys_path!r})'.format(self)

    @property
    def sys_path(self):
        """
        Absolute path of this device in ``sysfs`` including the mount point.
        """
        return libudev.udev_device_get_syspath(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def dev_path(self):
        """
        Kernel device path.

        Unlike :attr:`sys_path`, this path does not contain the mount point.
        However, the path is absolute and starts with a slash ``'/'``.
        """
        return libudev.udev_device_get_devpath(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def subsystem(self):
        """
        Name of the subsystem, this device is part of.
        """
        return libudev.udev_device_get_subsystem(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def sys_name(self):
        """
        Device name inside ``sysfs``.
        """
        return libudev.udev_device_get_sysname(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def dev_node(self):
        """
        Absolute path to the device node (including the device directory).
        """
        return libudev.udev_device_get_devnode(self._device).decode(
            sys.getfilesystemencoding())

    @property
    def devlinks(self):
        """
        Return all device file links in the device directory, which point to
        this device.
        """
        entry = libudev.udev_device_get_devlinks_list_entry(self._device)
        while entry:
            yield libudev.udev_list_entry_get_name(entry).decode(
                sys.getfilesystemencoding())
            entry = libudev.udev_list_entry_get_next(entry)

    def __iter__(self):
        entry = libudev.udev_device_get_properties_list_entry(self._device)
        while entry:
            yield libudev.udev_list_entry_get_name(entry).decode(
                sys.getfilesystemencoding())
            entry = libudev.udev_list_entry_get_next(entry)

    def __len__(self):
        return len(list(self))

    def __getitem__(self, property):
        """
        Get a property from this device.
        """
        value = libudev.udev_device_get_property_value(
            self._device, _assert_bytes(property))
        if value is None:
            raise KeyError('No such property: {0}'.format(property))
        value = _property_value_from_bytes(value)
        if property == 'DEVLINKS':
            # special handle for device links list
            return value.split(' ')
        return value

    def __eq__(self, other):
        return self.dev_path == other.dev_path

    def __ne__(self, other):
        return self.dev_path != other.dev_path
<|endoftext|>


<commit_before>from udsoncan import services
from udsoncan.exceptions import *

from test.ClientServerTest import ClientServerTest

class TestRequestSeed(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

#========================================
	def test_request_seed_success(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x05\x99\x88\x77\x66")	# Positive response

	def _test_request_seed_success(self):
		seed = self.udsclient.request_seed(0x05)
		self.assertEqual(seed, b"\x99\x88\x77\x66")

#========================================
	def test_request_seed_denied(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x7F\x22")	# Conditions Not Correct

	def _test_request_seed_denied(self):
		with self.assertRaises(NegativeResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)
		response = handle.exception.response

		self.assertTrue(response.valid)
		self.assertTrue(issubclass(response.service, services.SecurityAccess))
		self.assertEqual(response.code, 0x22)

#========================================
	def test_request_seed_bad_subfn(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x06\x99\x88\x77\x66")	# Positive response with wrong subfunction

	def _test_request_seed_bad_subfn(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_incomplete_response(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x05")	# Positive response with no seed

	def _test_request_seed_incomplete_response(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_invalidservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x00\x05") #Inexistent Service

	def _test_request_seed_invalidservice(self):
		with self.assertRaises(InvalidResponseException) as handle:
			response = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_wrongservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x7E\x00") # Valid but wrong service (Tester Present)

	def _test_request_seed_wrongservice(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			response = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_bad_param(self):
		pass

	def _test_request_seed_bad_param(self):
		with self.assertRaises(ValueError):
			response = self.udsclient.request_seed(0x80)

		with self.assertRaises(ValueError):
			response = self.udsclient.request_seed(-1)

#============================================================================
#============================================================================

class TestSendKey(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

	def test_send_key_success(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x06")	# Positive response

	def _test_send_key_success(self):
		success = self.udsclient.send_key(0x06,b"\x11\x22\x33\x44")
		self.assertTrue(success)

#========================================
	def test_send_key_denied(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x7F\x35")	# InvalidKey

	def _test_send_key_denied(self):
		with self.assertRaises(NegativeResponseException) as handle:
			success = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")
		response = handle.exception.response

		self.assertTrue(response.valid)
		self.assertTrue(issubclass(response.service, services.SecurityAccess))
		self.assertEqual(response.code, 0x35)

#========================================
	def test_send_key_bad_subfn(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x08\x99\x88\x77\x66")	# Positive response with wrong subfunction

	def _test_send_key_bad_subfn(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			success = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_invalidservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x00\x06") #Inexistent Service

	def _test_send_key_invalidservice(self):
		with self.assertRaises(InvalidResponseException) as handle:
			response = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_wrongservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x7E\x00") # Valid but wrong service (Tester Present)

	def _test_send_key_wrongservice(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			response = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_bad_param(self):
		pass

	def _test_send_key_bad_param(self):
		with self.assertRaises(ValueError):
			response = self.udsclient.send_key(0x80, b"\x11\x22\x33\x44")

		with self.assertRaises(ValueError):
			response = self.udsclient.send_key(-1, b"\x11\x22\x33\x44")

#============================================================================
#============================================================================

class TestUnlockSecurityService(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

	def dummy_algo(self, seed):
		key = bytearray(seed)
		for i in range(len(key)):
			key[i] ^= 0xFF
		return key

	def test_unlock_success(self):
		for i in range(2):
			request = self.conn.touserqueue.get(timeout=1)
			self.assertEqual(request, b"\x27\x07")		# Request seed
			self.conn.fromuserqueue.put(b"\x67\x07\x11\x22\x33\x44")	# Positive response
			request = self.conn.touserqueue.get(timeout=1)
			self.conn.fromuserqueue.put(b"\x67\x08\xEE\xDD\xCC\xBB")	# Send Key
			self.conn.fromuserqueue.put(b"\x67\x08")	# Positive response

	def _test_unlock_success(self):
		self.udsclient.config['security_algo'] = self.dummy_algo
		success = self.udsclient.unlock_security_access(0x07)
		self.assertTrue(success)

		success = self.udsclient.unlock_security_access(0x08)
		self.assertTrue(success)

	def test_no_algo_set(self):
		pass

	def _test_no_algo_set(self):
		with self.assertRaises(NotImplementedError):
			self.udsclient.unlock_security_access(0x07)<commit_msg>bugfix in security access unittest<commit_after>from udsoncan import services
from udsoncan.exceptions import *

from test.ClientServerTest import ClientServerTest

class TestRequestSeed(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

#========================================
	def test_request_seed_success(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x05\x99\x88\x77\x66")	# Positive response

	def _test_request_seed_success(self):
		seed = self.udsclient.request_seed(0x05)
		self.assertEqual(seed, b"\x99\x88\x77\x66")

#========================================
	def test_request_seed_denied(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x7F\x22")	# Conditions Not Correct

	def _test_request_seed_denied(self):
		with self.assertRaises(NegativeResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)
		response = handle.exception.response

		self.assertTrue(response.valid)
		self.assertTrue(issubclass(response.service, services.SecurityAccess))
		self.assertEqual(response.code, 0x22)

#========================================
	def test_request_seed_bad_subfn(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x06\x99\x88\x77\x66")	# Positive response with wrong subfunction

	def _test_request_seed_bad_subfn(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_incomplete_response(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x67\x05")	# Positive response with no seed

	def _test_request_seed_incomplete_response(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			seed = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_invalidservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x00\x05") #Inexistent Service

	def _test_request_seed_invalidservice(self):
		with self.assertRaises(InvalidResponseException) as handle:
			response = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_wrongservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x05")
		self.conn.fromuserqueue.put(b"\x7E\x00") # Valid but wrong service (Tester Present)

	def _test_request_seed_wrongservice(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			response = self.udsclient.request_seed(0x05)

#========================================
	def test_request_seed_bad_param(self):
		pass

	def _test_request_seed_bad_param(self):
		with self.assertRaises(ValueError):
			response = self.udsclient.request_seed(0x80)

		with self.assertRaises(ValueError):
			response = self.udsclient.request_seed(-1)

#============================================================================
#============================================================================

class TestSendKey(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

	def test_send_key_success(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x06")	# Positive response

	def _test_send_key_success(self):
		success = self.udsclient.send_key(0x06,b"\x11\x22\x33\x44")
		self.assertTrue(success)

#========================================
	def test_send_key_denied(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x7F\x35")	# InvalidKey

	def _test_send_key_denied(self):
		with self.assertRaises(NegativeResponseException) as handle:
			success = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")
		response = handle.exception.response

		self.assertTrue(response.valid)
		self.assertTrue(issubclass(response.service, services.SecurityAccess))
		self.assertEqual(response.code, 0x35)

#========================================
	def test_send_key_bad_subfn(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x67\x08\x99\x88\x77\x66")	# Positive response with wrong subfunction

	def _test_send_key_bad_subfn(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			success = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_invalidservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x00\x06") #Inexistent Service

	def _test_send_key_invalidservice(self):
		with self.assertRaises(InvalidResponseException) as handle:
			response = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_wrongservice(self):
		request = self.conn.touserqueue.get(timeout=1)
		self.assertEqual(request, b"\x27\x06\x11\x22\x33\x44")
		self.conn.fromuserqueue.put(b"\x7E\x00") # Valid but wrong service (Tester Present)

	def _test_send_key_wrongservice(self):
		with self.assertRaises(UnexpectedResponseException) as handle:
			response = self.udsclient.send_key(0x06, b"\x11\x22\x33\x44")

#========================================
	def test_send_key_bad_param(self):
		pass

	def _test_send_key_bad_param(self):
		with self.assertRaises(ValueError):
			response = self.udsclient.send_key(0x80, b"\x11\x22\x33\x44")

		with self.assertRaises(ValueError):
			response = self.udsclient.send_key(-1, b"\x11\x22\x33\x44")

#============================================================================
#============================================================================

class TestUnlockSecurityService(ClientServerTest):
	def __init__(self, *args, **kwargs):
		ClientServerTest.__init__(self, *args, **kwargs)

	def dummy_algo(self, seed):
		key = bytearray(seed)
		for i in range(len(key)):
			key[i] ^= 0xFF
		return key

	def test_unlock_success(self):
		for i in range(2):
			request = self.conn.touserqueue.get(timeout=1)
			self.assertEqual(request, b"\x27\x07")		# Request seed
			self.conn.fromuserqueue.put(b"\x67\x07\x11\x22\x33\x44")	# Positive response
			request = self.conn.touserqueue.get(timeout=1)
			self.assertEqual(request, b"\x27\x08\xEE\xDD\xCC\xBB")
			self.conn.fromuserqueue.put(b"\x67\x08")	# Positive response

	def _test_unlock_success(self):
		self.udsclient.config['security_algo'] = self.dummy_algo
		success = self.udsclient.unlock_security_access(0x07)
		self.assertTrue(success)

		success = self.udsclient.unlock_security_access(0x08)
		self.assertTrue(success)

	def test_no_algo_set(self):
		pass

	def _test_no_algo_set(self):
		with self.assertRaises(NotImplementedError):
			self.udsclient.unlock_security_access(0x07)<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template

import settings

admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^registration/', include('registration.urls')),
    (r'^$', direct_to_template,
        { 'template': 'index.html' }, 'index'),
)

if settings.STATIC_SERVE:
    urlpatterns += patterns('',
        url(
            regex = r'^media/(?P<path>.*)$',
            view = 'django.views.static.serve',
            kwargs = {'document_root': settings.MEDIA_ROOT}),
    )
<commit_msg>Move pages from registration to accounts/<commit_after>from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template

import settings

admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    (r'^accounts/', include('registration.urls')),
    (r'^$', direct_to_template,
        { 'template': 'index.html' }, 'index'),
)

if settings.STATIC_SERVE:
    urlpatterns += patterns('',
        url(
            regex = r'^media/(?P<path>.*)$',
            view = 'django.views.static.serve',
            kwargs = {'document_root': settings.MEDIA_ROOT}),
    )
<|endoftext|>


<commit_before>"""
URLConf for Django user registration.

Recommended usage is to use a call to ``include()`` in your
project's root URLConf to include this URLConf for any URL
begninning with '/accounts/'.

"""

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth.views import login, logout
from views import activate, register

urlpatterns = patterns('',
                       (r'^activate/(?P<activation_key>[a-fA-F0-9]+)/$', activate),
                       (r'^login/$', login, {'template_name': 'registration/login.html'}),
                       (r'^logout/$', logout, {'template_name': 'registration/logout.html'}),
                       (r'^register/$', register),
                       (r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}),
                       )
<commit_msg>Flip the activation URLConf back to match on \w+ and add a comment explaining why.<commit_after>"""
URLConf for Django user registration.

Recommended usage is to use a call to ``include()`` in your
project's root URLConf to include this URLConf for any URL
begninning with '/accounts/'.

"""

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth.views import login, logout
from views import activate, register

urlpatterns = patterns('',
                       # Activation keys get matched by \w+ instead of the more specific
                       # [a-fA-F0-9]+ because a bad activation key should still get to the view;
                       # that way it can return a sensible "invalid key" message instead of a
                       # confusing 404.
                       (r'^activate/(?P<activation_key>\w+)/$', activate),
                       (r'^login/$', login, {'template_name': 'registration/login.html'}),
                       (r'^logout/$', logout, {'template_name': 'registration/logout.html'}),
                       (r'^register/$', register),
                       (r'^register/complete/$', direct_to_template, {'template': 'registration/registration_complete.html'}),
                       )
<|endoftext|>


<commit_before>"""
Recommended usage is to use a call to ``include()`` in your
project's root URLConf to include this URLConf for any URL
beginning with '/snippets/'.

"""

from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_list
from django.contrib.auth.models import User
from models import Language, Snippet, Tag
from views import bookmarks, snippets

tag_info_dict = {
    'queryset': Tag.objects.all(),
    'paginate_by': 20,
    }

language_info_dict = {
    'queryset': Language.objects.all(),
    'paginate_by': 20,
    }

user_info_dict = {
    'queryset': User.objects.all(),
    'paginate_by': 20,
    'template_name': 'snippets/user_list.html',
    }

snippet_info_dict = {
    'queryset': Snippet.objects.all(),
    'paginate_by': 20,
    }

urlpatterns = patterns('',
                       (r'^languages/(?P<slug>[\w-]+)', snippets.snippets_by_language),
                       (r'^add/$', snippets.add_snippet),
                       (r'^edit/(?P<snippet_id>\d+)/$', snippets.edit_snippet),
                       (r'^(?P<snippet_id>\d+)/$', snippets.snippet_detail),
                       (r'^rate/(?P<snippet_id>\d+)/$', snippets.rate_snippet),
                       (r'^tags/(?P<slug>[\w-]+)/$', snippets.snippets_by_tag),
                       (r'^users/(?P<username>\w+)/$', snippets.snippets_by_author),
                       )

urlpatterns += patterns('',
                        (r'^bookmarks/$', bookmarks.bookmarks),
                        (r'^bookmarks/add/(?P<snippet_id>\d+)/$', bookmarks.add_bookmark),
                        (r'^bookmarks/author/(?P<author_username>[\w-]+)/$', bookmarks.bookmarks_by_author),
                        (r'^bookmarks/delete/(?P<bookmark_id>\d+)/$', bookmarks.delete_bookmark),
                        (r'^bookmarks/language/(?P<language_slug>[\w-]+)/$', bookmarks.bookmarks_by_language),
                        (r'^bookmarks/tag/(?P<tag_slug>[\w-]+)/$', bookmarks_by_tag),
                        )

urlpatterns += patterns('',
                        (r'^languages/$', object_list, language_info_dict),
                        (r'^$', object_list, snippet_info_dict),
                        (r'^tags/$', object_list, tag_info_dict),
                        (r'^users/$', object_list, user_info_dict),
                        )
<commit_msg>Minor URLConf rearrangement<commit_after>"""
URLConf for Cab.

Recommended usage is to use a call to ``include()`` in your
project's root URLConf to include this URLConf for any URL
beginning with '/snippets/'.

"""

from django.conf.urls.defaults import *
from django.views.generic.list_detail import object_list
from django.contrib.auth.models import User
from models import Language, Snippet, Tag
from views import bookmarks, snippets

# Info for generic views.
tag_info_dict = {
    'queryset': Tag.objects.all(),
    'paginate_by': 20,
    }

language_info_dict = {
    'queryset': Language.objects.all(),
    'paginate_by': 20,
    }

user_info_dict = {
    'queryset': User.objects.all(),
    'paginate_by': 20,
    'template_name': 'snippets/user_list.html',
    }

snippet_info_dict = {
    'queryset': Snippet.objects.all(),
    'paginate_by': 20,
    }

# General snippets views.
urlpatterns = patterns('',
                       (r'^(?P<snippet_id>\d+)/$', snippets.snippet_detail),
                       (r'^add/$', snippets.add_snippet),
                       (r'^edit/(?P<snippet_id>\d+)/$', snippets.edit_snippet),
                       (r'^languages/(?P<slug>[\w-]+)', snippets.snippets_by_language),
                       (r'^rate/(?P<snippet_id>\d+)/$', snippets.rate_snippet),
                       (r'^tags/(?P<slug>[\w-]+)/$', snippets.snippets_by_tag),
                       (r'^users/(?P<username>\w+)/$', snippets.snippets_by_author),
                       )

# Views that work with bookmarks.
urlpatterns += patterns('',
                        (r'^bookmarks/$', bookmarks.bookmarks),
                        (r'^bookmarks/add/(?P<snippet_id>\d+)/$', bookmarks.add_bookmark),
                        (r'^bookmarks/author/(?P<author_username>[\w-]+)/$', bookmarks.bookmarks_by_author),
                        (r'^bookmarks/delete/(?P<bookmark_id>\d+)/$', bookmarks.delete_bookmark),
                        (r'^bookmarks/language/(?P<language_slug>[\w-]+)/$', bookmarks.bookmarks_by_language),
                        (r'^bookmarks/tag/(?P<tag_slug>[\w-]+)/$', bookmarks_by_tag),
                        )

# Generic views.
urlpatterns += patterns('',
                        (r'^$', object_list, snippet_info_dict),
                        (r'^languages/$', object_list, language_info_dict),
                        (r'^tags/$', object_list, tag_info_dict),
                        (r'^users/$', object_list, user_info_dict),
                        )
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
import os
from corehq.apps.domain.utils import legacy_domain_re

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
try:
    from localsettings import LOCAL_APP_URLS
except:
    LOCAL_APP_URLS = ()
admin.autodiscover()

handler500 = 'corehq.apps.hqwebapp.views.server_error'
handler404 = 'corehq.apps.hqwebapp.views.not_found'

from corehq.apps.hqwebapp.urls import domain_specific as hqwebapp_domain_specific
from corehq.apps.domain.urls import domain_specific as domain_domain_specific
domain_specific = patterns('',
    (r'^apps/', include('corehq.apps.app_manager.urls')),
    # the receiver needs to accept posts at an endpoint that might
    # not have a slash, so don't include it at the root urlconf
    (r'^receiver', include('corehq.apps.receiverwrapper.urls')),
    (r'^migration/', include('corehq.apps.migration.urls')),
    (r'^users/', include('corehq.apps.users.urls')),
    (r'^groups/', include('corehq.apps.groups.urls')),
    (r'^phone/', include('corehq.apps.ota.urls')),
    (r'^sms/', include('corehq.apps.sms.urls')),
    (r'^reminders/', include('corehq.apps.reminders.urls')),
    (r'^reports/', include('corehq.apps.reports.urls')),
    # include only those urls in hqwebapp which are domain-specific
    (r'^domain/', include(domain_domain_specific)),
    (r'^', include(hqwebapp_domain_specific)),
    (r'^', include('django_user_registration.urls')),
    (r'^case/', include('corehq.apps.hqcase.urls')),
    (r'^submitlist/', include('corehq.apps.hqsofabed.urls')),
    (r'^cleanup/', include('corehq.apps.cleanup.urls')),
    (r'^phonelog/', include('phonelog.urls')),
    (r'^customreports/', include('pathfinder.urls')),
)

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^auditcare/', include('auditcare.urls')),
    (r'^a/(?P<domain>%s)/' % legacy_domain_re, include(domain_specific)),
    (r'^couch/', include('djangocouch.urls')),
    (r'^xep/', include('xep_hq_server.urls')),
    (r'^webforms/', include('touchforms.formplayer.urls')),
    (r'', include('corehq.apps.hqwebapp.urls')),
    (r'', include('corehq.apps.domain.urls')),
    (r'^hq/admin/', include('corehq.apps.hqadmin.urls')),
    (r'^hq/prescriptions/', include('corehq.apps.prescriptions.urls')),
    (r'^couchlog/', include('couchlog.urls')),
    (r'^formtranslate/', include('formtranslate.urls')),
    (r'^unicel/', include('corehq.apps.unicel.urls')),
    (r'^langcodes/', include('langcodes.urls')),
    (r'^builds/', include('corehq.apps.builds.urls')),
    (r'^downloads/temp/', include('soil.urls')),
    (r'^test/CommCare.jar', 'corehq.apps.app_manager.views.download_test_jar'),
    (r'^translations/', include('corehq.apps.translations.urls')),
) + patterns('', *LOCAL_APP_URLS)

#django-staticfiles static/ url mapper
if settings.DEBUG:
    urlpatterns += patterns('staticfiles.views',
        url(r'^static/(?P<path>.*)$', 'serve'),
    )

<commit_msg>Remove pathfinder report custom URL.<commit_after>from django.conf.urls.defaults import *
from django.conf import settings
import os
from corehq.apps.domain.utils import legacy_domain_re

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
try:
    from localsettings import LOCAL_APP_URLS
except:
    LOCAL_APP_URLS = ()
admin.autodiscover()

handler500 = 'corehq.apps.hqwebapp.views.server_error'
handler404 = 'corehq.apps.hqwebapp.views.not_found'

from corehq.apps.hqwebapp.urls import domain_specific as hqwebapp_domain_specific
from corehq.apps.domain.urls import domain_specific as domain_domain_specific
domain_specific = patterns('',
    (r'^apps/', include('corehq.apps.app_manager.urls')),
    # the receiver needs to accept posts at an endpoint that might
    # not have a slash, so don't include it at the root urlconf
    (r'^receiver', include('corehq.apps.receiverwrapper.urls')),
    (r'^migration/', include('corehq.apps.migration.urls')),
    (r'^users/', include('corehq.apps.users.urls')),
    (r'^groups/', include('corehq.apps.groups.urls')),
    (r'^phone/', include('corehq.apps.ota.urls')),
    (r'^sms/', include('corehq.apps.sms.urls')),
    (r'^reminders/', include('corehq.apps.reminders.urls')),
    (r'^reports/', include('corehq.apps.reports.urls')),
    # include only those urls in hqwebapp which are domain-specific
    (r'^domain/', include(domain_domain_specific)),
    (r'^', include(hqwebapp_domain_specific)),
    (r'^', include('django_user_registration.urls')),
    (r'^case/', include('corehq.apps.hqcase.urls')),
    (r'^submitlist/', include('corehq.apps.hqsofabed.urls')),
    (r'^cleanup/', include('corehq.apps.cleanup.urls')),
    (r'^phonelog/', include('phonelog.urls')),
)

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^auditcare/', include('auditcare.urls')),
    (r'^a/(?P<domain>%s)/' % legacy_domain_re, include(domain_specific)),
    (r'^couch/', include('djangocouch.urls')),
    (r'^xep/', include('xep_hq_server.urls')),
    (r'^webforms/', include('touchforms.formplayer.urls')),
    (r'', include('corehq.apps.hqwebapp.urls')),
    (r'', include('corehq.apps.domain.urls')),
    (r'^hq/admin/', include('corehq.apps.hqadmin.urls')),
    (r'^hq/prescriptions/', include('corehq.apps.prescriptions.urls')),
    (r'^couchlog/', include('couchlog.urls')),
    (r'^formtranslate/', include('formtranslate.urls')),
    (r'^unicel/', include('corehq.apps.unicel.urls')),
    (r'^langcodes/', include('langcodes.urls')),
    (r'^builds/', include('corehq.apps.builds.urls')),
    (r'^downloads/temp/', include('soil.urls')),
    (r'^test/CommCare.jar', 'corehq.apps.app_manager.views.download_test_jar'),
    (r'^translations/', include('corehq.apps.translations.urls')),
) + patterns('', *LOCAL_APP_URLS)

#django-staticfiles static/ url mapper
if settings.DEBUG:
    urlpatterns += patterns('staticfiles.views',
        url(r'^static/(?P<path>.*)$', 'serve'),
    )

<|endoftext|>


<commit_before>"""
Class to serve the results of an on-going real-time analysis and make them
available upon request.

This tool is designed to run in a separate thread, where it will:
    - Listen for incoming requests from clients (e.g. experimental presentation
    software)
    - Check to see if the requested information is available
    - Return the requested information (or a message indicating it is not
    available yet)

Elsewhere, Pyneal uses the powerful Zmq socket library for network communication,
however in this case the results server needs to be able to talk to clients that
are connecting using 'normal' socket libraries that are incompatible with ZMQ.
Thus, the results server is a traditional TCP socket server.

Message format:
Incoming requests from clients should take the form: XXXXXX

Responses from the server will be JSON strings like:
    If the results from the requested volume exist:
        {'foundResults': True, 'data': [val1, val2, ... ] }
    If they don't:
        {'foundResults': False}

"""
# python 2/3 compatibility
from __future__ import print_function

import os
import sys
import logging
import json
import atexit
from threading import Thread

import numpy as np
import socket

class ResultsServer(Thread):
    """
    Class to serve results from real-time analysis. This server will accept
    connections from remote clients, check if the requested results are available,
    and return a JSON-formatted message
    """

    def __init__(self, host='127.0.0.1', port=5556):
        # start the thread upon creation
        Thread.__init__(self)

        # set up logger
        self.logger = logging.getLogger('PynealLog')

        # configuration parameters
        self.alive = True
        self.results = {}       # store results in dict {'vol#':{results}}
        self.host = host
        self.port = port
        self.maxClients = 1

        # launch server
        self.resultsSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.resultsSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.resultsSocket.bind((self.host, self.port))
        self.resultsSocket.listen(self.maxClients)
        self.logger.debug('Results Server bound to {}:{}'.format(self.host, self.port))
        self.logger.info('Results Server alive and listening....')

        # atexit function, shut down server
        atexit.register(self.killServer)

    def run(self):
        """
        Run server, listening for requests and returning responses to clients
        """
        while self.alive:
            ### Listen for new connections, redirect clients to new socket
            connection, address = self.resultsSocket.accept()
            print('client connected!')

            ### Get the requested volume (should be a 4-char string representing
            # volume number, e.g. '0001')
            recvMsg = connection.recv(4).decode()
            self.logger.debug('Received request: {}'.format(recvMsg))

            # reformat the requested volume to remove any leading 0s
            requestedVol = str(int(recvMsg))

            ### Look up the results for the requested volume
            volResults = self.requestLookup(requestedVol)

            ### Send the results to the client

                self.sendResults(connection, volResults)
            else:
                self.sendResults(connection, 'None')
            result = {'response':'no'}
            connection.send(json.dumps(result).encode())

            self.logger.debug('Sent result: {}'.format(result))

            # close client connection
            connection.close()

    def updateResults(self, vol, volResults):
        """
        Add the supplied result to the results dictionary.
            - vol: the volume number associated with this result
            - volResults: dictionary containing all of the results for this volume
        """
        self.results[str(vol)] = volResults
        self.logger.debug('vol {} - {} added to resultsServer'.format(vol, volResults))

    def requestLookup(self, vol):
        """
        Check to see if there are results for the requested volume. Will return a
        dictionary of results for this volume. At a minimum, the dictionary will
        contain an entry with the key 'foundResults' and the value is True or
        False based on whether there are any results for this volume.
        """
        if str(vol) in self.results.keys():
            theseResults = self.results[str(vol)]
            theseResults['foundResults'] = True
        else:
            theseResults = {'foundResults':False}
        return theseResults

    def killServer(self):
        self.alive = False

if __name__ == '__main__':
    port = 5556

    resultsServer = ResultsServer(port=port)
    #resultsServer.daemon = True
    resultsServer.start()
    print('Results Server alive and listening...')
<commit_msg>cleaned up documentation on resultsServer<commit_after>"""
Class to serve the results of an on-going real-time analysis and make them
available upon request.

This tool is designed to run in a separate thread, where it will:
    - Listen for incoming requests from clients (e.g. experimental presentation
    software)
    - Check to see if the requested information is available
    - Return the requested information (or a message indicating it is not
    available yet)

Elsewhere, Pyneal uses the powerful Zmq socket library for network communication,
however in this case the results server needs to be able to talk to clients that
are connecting using 'normal' socket libraries that are incompatible with ZMQ.
Thus, the results server is a traditional TCP socket server.

** Message formats *********************
Incoming requests from clients should be 4-character strings representing the
requested volume number (zero padding to make 4-characters). E.g. '0001'

Responses from the server will be JSON strings:
    If the results from the requested volume exist:
        e.g. {'foundResults': True, 'average':2432}
    If they don't:
        {'foundResults': False}
At a minimum, the response will contain the 'foundResults' entry. If foundResults
is true, the remaining entries are all of the key:value pairs that were output during
the analysis stage for this volume

"""

# python 2/3 compatibility
from __future__ import print_function

import os
import sys
import logging
import json
import atexit
from threading import Thread

import numpy as np
import socket

class ResultsServer(Thread):
    """
    Class to serve results from real-time analysis. This server will accept
    connections from remote clients, check if the requested results are available,
    and return a JSON-formatted message
    """

    def __init__(self, host='127.0.0.1', port=5556):
        # start the thread upon creation
        Thread.__init__(self)

        # set up logger
        self.logger = logging.getLogger('PynealLog')

        # configuration parameters
        self.alive = True
        self.results = {}       # store results in dict {'vol#':{results}}
        self.host = host
        self.port = port
        self.maxClients = 1

        # launch server
        self.resultsSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.resultsSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.resultsSocket.bind((self.host, self.port))
        self.resultsSocket.listen(self.maxClients)
        self.logger.debug('Results Server bound to {}:{}'.format(self.host, self.port))
        self.logger.info('Results Server alive and listening....')

        # atexit function, shut down server
        atexit.register(self.killServer)

    def run(self):
        """
        Run server, listening for requests and returning responses to clients
        """
        while self.alive:
            ### Listen for new connections, redirect clients to new socket
            connection, address = self.resultsSocket.accept()
            print('client connected!')

            ### Get the requested volume (should be a 4-char string representing
            # volume number, e.g. '0001')
            recvMsg = connection.recv(4).decode()
            self.logger.debug('Received request: {}'.format(recvMsg))

            # reformat the requested volume to remove any leading 0s
            requestedVol = str(int(recvMsg))

            ### Look up the results for the requested volume
            volResults = self.requestLookup(requestedVol)

            ### Send the results to the client
            self.sendResults(connection, volResults)

            result = {'response':'no'}
            connection.send(json.dumps(result).encode())

            self.logger.debug('Sent result: {}'.format(result))

            # close client connection
            connection.close()

    def updateResults(self, vol, volResults):
        """
        Add the supplied result to the results dictionary.
            - vol: the volume number associated with this result
            - volResults: dictionary containing all of the results for this volume
        """
        self.results[str(vol)] = volResults
        self.logger.debug('vol {} - {} added to resultsServer'.format(vol, volResults))

    def requestLookup(self, vol):
        """
        Check to see if there are results for the requested volume. Will return a
        dictionary of results for this volume. At a minimum, the dictionary will
        contain an entry with the key 'foundResults' and the value is True or
        False based on whether there are any results for this volume.
        """
        if str(vol) in self.results.keys():
            theseResults = self.results[str(vol)]
            theseResults['foundResults'] = True
        else:
            theseResults = {'foundResults':False}
        return theseResults

    def killServer(self):
        self.alive = False

if __name__ == '__main__':
    port = 5556

    resultsServer = ResultsServer(port=port)
    #resultsServer.daemon = True
    resultsServer.start()
    print('Results Server alive and listening...')
<|endoftext|>


<commit_before>from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.base import TemplateView
from django.views.generic.simple import direct_to_template

from django.contrib import admin
admin.autodiscover()

from homepage.views import homepage
from package.views import package_autocomplete, category

urlpatterns = patterns("",

    url('', include('social_auth.urls')),
    url(r"^$", homepage, name="home"),
    url(r"^admin/", include(admin.site.urls)),
    url(r"^profiles/", include("profiles.urls")),
    url(r"^packages/", include("package.urls")),
    url(r"^grids/", include("grid.urls")),
    url(r"^feeds/", include("feeds.urls")),

    url(r"^categories/(?P<slug>[-\w]+)/$", category, name="category"),
    url(r"^categories/$", homepage, name="categories"),

    url(regex=r'^login/$', view=TemplateView.as_view(template_name= 'pages/login.html'), name='login',),
    url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', {}, 'logout',),

    # static pages
    url(r"^about/$", TemplateView.as_view(template_name='pages/about.html'), name="about"),
    url(r"^terms/$", TemplateView.as_view(template_name='pages/terms.html'), name="terms"),
    url(r"^faq/$", TemplateView.as_view(template_name='pages/faq.html'), name="faq"),
    url(r"^syndication/$", direct_to_template, {"template": "pages/syndication.html"}, name="syndication"),
    url(r"^contribute/$", direct_to_template, {"template": "pages/contribute.html"}, name="contribute"),
    url(r"^search/", include("searchv2.urls")),
    url(r"^importer/", include("importer.urls")),
)

from apiv1.api import Api
from apiv1.resources import (
                    GotwResource, DpotwResource,
                    PackageResource, CategoryResource,
                    GridResource, PackageResourceBase,
                    UserResource
                    )

v1_api = Api()
v1_api.register(PackageResourceBase())
v1_api.register(PackageResource())
v1_api.register(CategoryResource())
v1_api.register(GridResource())
v1_api.register(GotwResource())
v1_api.register(DpotwResource())
v1_api.register(UserResource())

urlpatterns += patterns('',
    url(r"^api/", include(v1_api.urls)),
)

if settings.SERVE_MEDIA:
    urlpatterns += patterns("",
        url(r"", include("django.contrib.staticfiles.urls")),
    )
<commit_msg>Finish lintification<commit_after>from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.base import TemplateView
from django.views.generic.simple import direct_to_template

from django.contrib import admin
admin.autodiscover()

from homepage.views import homepage
from package.views import package_autocomplete, category

urlpatterns = patterns("",

    url('', include('social_auth.urls')),
    url(r"^$", homepage, name="home"),
    url(r"^admin/", include(admin.site.urls)),
    url(r"^profiles/", include("profiles.urls")),
    url(r"^packages/", include("package.urls")),
    url(r"^grids/", include("grid.urls")),
    url(r"^feeds/", include("feeds.urls")),

    url(r"^categories/(?P<slug>[-\w]+)/$", category, name="category"),
    url(r"^categories/$", homepage, name="categories"),

    url(regex=r'^login/$', view=TemplateView.as_view(template_name= 'pages/login.html'), name='login',),
    url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', {}, 'logout',),

    # static pages
    url(r"^about/$", TemplateView.as_view(template_name='pages/about.html'), name="about"),
    url(r"^terms/$", TemplateView.as_view(template_name='pages/terms.html'), name="terms"),
    url(r"^faq/$", TemplateView.as_view(template_name='pages/faq.html'), name="faq"),
    url(r"^syndication/$", TemplateView.as_view(template_name='pages/syndication.html'), name="syndication"),
    url(r"^contribute/$", TemplateView.as_view(template_name='pages/contribute.html'), name="contribute"),
    url(r"^search/", include("searchv2.urls")),
    url(r"^importer/", include("importer.urls")),
)

from apiv1.api import Api
from apiv1.resources import (
                    GotwResource, DpotwResource,
                    PackageResource, CategoryResource,
                    GridResource, PackageResourceBase,
                    UserResource
                    )

v1_api = Api()
v1_api.register(PackageResourceBase())
v1_api.register(PackageResource())
v1_api.register(CategoryResource())
v1_api.register(GridResource())
v1_api.register(GotwResource())
v1_api.register(DpotwResource())
v1_api.register(UserResource())

urlpatterns += patterns('',
    url(r"^api/", include(v1_api.urls)),
)

if settings.SERVE_MEDIA:
    urlpatterns += patterns("",
        url(r"", include("django.contrib.staticfiles.urls")),
    )
<|endoftext|>


<commit_before>from django.conf.urls.defaults import *
from django.conf import settings
import os

from corehq.util.modules import try_import

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

admin.autodiscover()

from corehq.apps.hqwebapp.urls import domain_specific as hqwebapp_domain_specific
domain_specific = patterns('',
    (r'^apps/', include('corehq.apps.app_manager.urls')),
    (r'^receiver', include('corehq.apps.receiver.urls')),
    (r'^data/', include('corehq.apps.new_data.urls')),
    (r'^users/', include('corehq.apps.users.urls')),
    (r'^reports/', include('corehq.apps.reports.urls')),
    (r'^', include(hqwebapp_domain_specific))

)

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^a/(?P<domain>\w+)/', include(domain_specific)),
    (r'^xep/', include('xep_hq_server.urls')),
    (r'', include('corehq.apps.hqwebapp.urls')),
    (r'', include('corehq.apps.domain.urls')),

)

# magic static media server (idea + implementation lifted from rapidsms)
for module_name in settings.INSTALLED_APPS:

    # leave django contrib apps alone. (many of them include urlpatterns
    # which shouldn't be auto-mapped.) this is a hack, but i like the
    # automatic per-app mapping enough to keep it. (for now.)
    if module_name.startswith("django."):
        continue

    # attempt to import this app's urls
    module = try_import("%s.urls" % (module_name))
    if not hasattr(module, "urlpatterns"): continue

    # TODO: the following is currently broken
    # add the explicitly defined urlpatterns
    # urlpatterns += module.urlpatterns

    # if the MEDIA_URL does not contain a hostname (ie, it's just an
    # http path), and we are running in DEBUG mode, we will also serve
    # the media for this app via this development server. in production,
    # these files should be served directly
    if settings.DEBUG:
        if not settings.MEDIA_URL.startswith("http://"):
            media_prefix = settings.MEDIA_URL.strip("/")
            module_suffix = module_name.split(".")[-1]

            # does urls.py have a sibling "static" dir? (media is always
            # served from "static", regardless of what MEDIA_URL says)
            module_path = os.path.dirname(module.__file__)
            static_dir = "%s/static" % (module_path)
            if os.path.exists(static_dir):

                # map to {{ MEDIA_URL }}/appname
                urlpatterns += patterns("", url(
                    "^%s/%s/(?P<path>.*)$" % (
                        media_prefix,
                        module_suffix),
                    "django.views.static.serve",
                    {"document_root": static_dir}
                ))

<commit_msg>add reference to django_user_registration.urls<commit_after>from django.conf.urls.defaults import *
from django.conf import settings
import os

from corehq.util.modules import try_import

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

admin.autodiscover()

domain_specific = patterns('',
    (r'^apps/', include('corehq.apps.app_manager.urls')),
    (r'^receiver', include('corehq.apps.receiver.urls')),
    (r'^data/', include('corehq.apps.new_data.urls')),
    (r'^users/', include('corehq.apps.users.urls')),
    (r'^reports/', include('corehq.apps.reports.urls')),
    (r'^', include('corehq.apps.hqwebapp.urls')),
    (r'^', include('django_user_registration.urls')),
)

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^a/(?P<domain>\w+)/', include(domain_specific)),
    (r'^xep/', include('xep_hq_server.urls')),
    (r'', include('corehq.apps.hqwebapp.urls')),
    (r'', include('corehq.apps.domain.urls')),
)

# magic static media server (idea + implementation lifted from rapidsms)
for module_name in settings.INSTALLED_APPS:

    # leave django contrib apps alone. (many of them include urlpatterns
    # which shouldn't be auto-mapped.) this is a hack, but i like the
    # automatic per-app mapping enough to keep it. (for now.)
    if module_name.startswith("django."):
        continue

    # attempt to import this app's urls
    module = try_import("%s.urls" % (module_name))
    if not hasattr(module, "urlpatterns"): continue

    # TODO: the following is currently broken
    # add the explicitly defined urlpatterns
    # urlpatterns += module.urlpatterns

    # if the MEDIA_URL does not contain a hostname (ie, it's just an
    # http path), and we are running in DEBUG mode, we will also serve
    # the media for this app via this development server. in production,
    # these files should be served directly
    if settings.DEBUG:
        if not settings.MEDIA_URL.startswith("http://"):
            media_prefix = settings.MEDIA_URL.strip("/")
            module_suffix = module_name.split(".")[-1]

            # does urls.py have a sibling "static" dir? (media is always
            # served from "static", regardless of what MEDIA_URL says)
            module_path = os.path.dirname(module.__file__)
            static_dir = "%s/static" % (module_path)
            if os.path.exists(static_dir):

                # map to {{ MEDIA_URL }}/appname
                urlpatterns += patterns("", url(
                    "^%s/%s/(?P<path>.*)$" % (
                        media_prefix,
                        module_suffix),
                    "django.views.static.serve",
                    {"document_root": static_dir}
                ))

<|endoftext|>


<commit_before>from django.conf.urls import include, url
from django.views.generic import RedirectView

from django.contrib import admin
admin.autodiscover()

import mendel.views
from mendel.models import Keyword, Category, Document, Context, Review
from django.contrib.auth.models import User

from rest_framework import routers, serializers, viewsets

class KeywordSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Keyword
        fields = ('__all__')

class KeyViewSet(viewsets.ModelViewSet):
    queryset = Keyword.objects.all()
    serializer_class = KeywordSerializer

class CategorySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Category
        fields = ('__all__')

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class ContextSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Context
        fields = ('__all__')
        depth = 1

class ContextViewSet(viewsets.ModelViewSet):
    queryset = Context.objects.all()
    serializer_class = ContextSerializer

class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Document
        fields = ('__all__')

class DocumentViewSet(viewsets.ModelViewSet):
    queryset = Document.objects.all()
    serializer_class = DocumentSerializer

class ReviewSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Review
        fields = ('__all__')
        depth = 1

class ReviewViewSet(viewsets.ModelViewSet):
    queryset = Review.objects.all()
    serializer_class = ReviewSerializer

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'is_staff')

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

router = routers.DefaultRouter()
router.register(r'keywords', KeyViewSet)
router.register(r'categories', CategoryViewSet)
router.register(r'documents', DocumentViewSet)
router.register(r'context', ContextViewSet)
router.register(r'reviews', ReviewViewSet)
router.register(r'users', UserViewSet)

urlpatterns = [
    url(r'^$', mendel.views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^api/', include(router.urls)),
    # TODO: Re-enable versioning of the API
    # url(r'^api/v1/', include(router.urls)),
    # url(r'^api/', RedirectView.as_view(url='/api/v1/')),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
<commit_msg>Use ModelSerializers instead of HyperlinkedModelSerializers<commit_after>from django.conf.urls import include, url
from django.views.generic import RedirectView

from django.contrib import admin
admin.autodiscover()

import mendel.views
from mendel.models import Keyword, Category, Document, Context, Review
from django.contrib.auth.models import User

from rest_framework import routers, serializers, viewsets

class KeywordSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ('id', 'name')

class KeyViewSet(viewsets.ModelViewSet):
    queryset = Keyword.objects.all()
    serializer_class = KeywordSerializer

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class ContextSerializer(serializers.ModelSerializer):
    keyword = KeywordSerializer()

    class Meta:
        model = Context
        fields = ('id', 'position_from', 'position_to', 'text', 'document', 'keyword')
        depth = 1

class ContextViewSet(viewsets.ModelViewSet):
    queryset = Context.objects.all()
    serializer_class = ContextSerializer

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = ('__all__')

class DocumentViewSet(viewsets.ModelViewSet):
    queryset = Document.objects.all()
    serializer_class = DocumentSerializer

class ReviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Review
        fields = ('__all__')

class ReviewViewSet(viewsets.ModelViewSet):
    queryset = Review.objects.all()
    serializer_class = ReviewSerializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'is_staff')

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

router = routers.DefaultRouter()
router.register(r'keywords', KeyViewSet)
router.register(r'categories', CategoryViewSet)
router.register(r'documents', DocumentViewSet)
router.register(r'context', ContextViewSet)
router.register(r'reviews', ReviewViewSet)
router.register(r'users', UserViewSet)

urlpatterns = [
    url(r'^$', mendel.views.index, name='index'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^api/', include(router.urls)),
    # TODO: Re-enable versioning of the API
    # url(r'^api/v1/', include(router.urls)),
    # url(r'^api/', RedirectView.as_view(url='/api/v1/')),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
<|endoftext|>


<commit_before>#!/usr/bin/env python

#  Copyright 2008-2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

USAGE = """robot.testdoc -- Robot Framework test data documentation tool

Version:  <VERSION>

Usage:  python -m robot.testdoc [options] data_sources output_file

This tool generates a high level test documentation from a given test data.
Generated documentation includes the names, documentations and other metadata
of each test suite and test case, as well as the top-level keywords and their
arguments. Most of the options accepted by this tool have exactly same
semantics as same options have when executing test cases.

Options
=======

  -T --title title       Set the title of the generated documentation.
                         Underscores in the title are converted to spaces.
  -N --name name         Set the name of the top level test suite.
  -D --doc document      Set the documentation of the top level test suite.
  -M --metadata name:value *  Set metadata of the top level test suite.
  -G --settag tag *      Set given tag(s) to all test cases.
  -t --test name *       Include test cases by name.
  -s --suite name *      Include test suites by name.
  -i --include tag *     Include test cases by tags.
  -e --exclude tag *     Exclude test cases by tags.
  -h -? --help           Print this help.

Examples
========

  python .m robot.testdoc mytestcases.html testdoc.html
  python .m robot.testdoc --name smoke_test_plan -i smoke path/to/my_tests/ doc.html
"""

import sys
import os
import codecs
import time

if 'robot' not in sys.modules:
    import pythonpathsetter   # running testdoc.py as script

from robot import utils
from robot.running import TestSuite, Keyword
from robot.conf import RobotSettings
from robot.parsing import populators
from robot.reporting.htmlfilewriter import HtmlFileWriter, ModelWriter
from robot.reporting.jsonwriter import JsonWriter

class TestDoc(utils.Application):

    def __init__(self):
        utils.Application.__init__(self, USAGE, arg_limits=(2,))

    def main(self, args, title=None, **options):
        datasources = args[0:-1]
        outfile = os.path.abspath(args[-1])
        suite = TestSuiteFactory(datasources, **options)
        self._write_test_doc(suite, outfile, title)
        self.console(outfile)

    def _write_test_doc(self, suite, outfile, title):
        output = codecs.open(outfile, 'w', 'UTF-8')
        model_writer = TestdocModelWriter(output, suite, title)
        HtmlFileWriter(output, model_writer).write('testdoc.html')
        output.close()

def TestSuiteFactory(datasources, **options):
    if isinstance(datasources, basestring):
        datasources = [datasources]
    populators.PROCESS_CURDIR = False
    try:
        return TestSuite(datasources, RobotSettings(options))
    finally:
        populators.PROCESS_CURDIR = True

class TestdocModelWriter(ModelWriter):

    def __init__(self, output, suite, title=None):
        self._output = output
        self._output_path = getattr(output, 'name', None)
        self._suite = suite
        self._title = title.replace('_', ' ') if title else ''

    def write(self, line):
        self._output.write('<script type="text/javascript">' + os.linesep)
        self.write_data()
        self._output.write('</script>' + os.linesep)

    def write_data(self):
        generated_time = time.localtime()
        model = {
            'suite': JsonConverter(self._output_path).convert(self._suite),
            'title': self._title,
            'generated': utils.format_time(generated_time, gmtsep=' '),
            'generatedMillis': long(time.mktime(generated_time) * 1000)
        }
        JsonWriter(self._output).write_json('testdoc = ', model)

class JsonConverter(object):

    def __init__(self, output_path=None):
        self._output_path = output_path

    def convert(self, suite):
        return self._convert_suite(suite)

    def _convert_suite(self, suite):
        return {
            'source': suite.source or '',
            'relativeSource': self._get_relative_source(suite.source),
            'id': suite.id,
            'name': suite.name,
            'fullName': suite.longname,
            'doc': suite.doc,
            'metadata': dict(suite.metadata),
            'numberOfTests': suite.get_test_count(),
            'suites': self._convert_suites(suite),
            'tests': self._convert_tests(suite),
            'keywords': list(self._convert_keywords(suite))
        }

    def _get_relative_source(self, source):
        if not source or not self._output_path:
            return ''
        return utils.get_link_path(source, os.path.dirname(self._output_path))

    def _convert_suites(self, suite):
        return [self._convert_suite(s) for s in suite.suites]

    def _convert_tests(self, suite):
        return [self._convert_test(t) for t in suite.tests]

    def _convert_test(self, test):
        return {
            'name': test.name,
            'fullName': test.longname,
            'id': test.id,
            'doc': test.doc,
            'tags': utils.normalize_tags(test.tags),
            'timeout': self._get_timeout(test.timeout),
            'keywords': list(self._convert_keywords(test))
        }

    def _convert_keywords(self, item):
        if item.setup.name:
            yield self._convert_keyword(item.setup, type='SETUP')
        for kw in getattr(item, 'keywords', []):
            yield self._convert_keyword(kw)
        if item.teardown.name:
            yield self._convert_keyword(item.teardown, type='TEARDOWN')

    def _convert_keyword(self, kw, type=None):
        return {
            'name': kw._get_name(kw.name) if isinstance(kw, Keyword) else kw.name,
            'arguments': ', '.join(kw.args),
            'type': type or {'kw': 'KEYWORD', 'for': 'FOR'}[kw.type]
        }

    def _get_timeout(self, timeout):
        try:
            tout = utils.secs_to_timestr(utils.timestr_to_secs(timeout.string))
        except ValueError:
            tout = timeout.string
        if timeout.message:
            tout += ' :: ' + timeout.message
        return tout

def testdoc_cli(args):
    """Executes testdoc similarly as from the command line.

    :param args: command line arguments as a list of strings.

    Example:
       testdoc_cli(['--title', 'Test Plan', 'mytests', 'plan.html'])
    """
    TestDoc().execute_cli(args)

if __name__ == '__main__':
    testdoc_cli(sys.argv[1:])
<commit_msg>testdoc: fix examples in help<commit_after>#!/usr/bin/env python

#  Copyright 2008-2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

USAGE = """robot.testdoc -- Robot Framework test data documentation tool

Version:  <VERSION>

Usage:  python -m robot.testdoc [options] data_sources output_file

This tool generates a high level test documentation from a given test data.
Generated documentation includes the names, documentations and other metadata
of each test suite and test case, as well as the top-level keywords and their
arguments. Most of the options accepted by this tool have exactly same
semantics as same options have when executing test cases.

Options
=======

  -T --title title       Set the title of the generated documentation.
                         Underscores in the title are converted to spaces.
  -N --name name         Set the name of the top level test suite.
  -D --doc document      Set the documentation of the top level test suite.
  -M --metadata name:value *  Set metadata of the top level test suite.
  -G --settag tag *      Set given tag(s) to all test cases.
  -t --test name *       Include test cases by name.
  -s --suite name *      Include test suites by name.
  -i --include tag *     Include test cases by tags.
  -e --exclude tag *     Exclude test cases by tags.
  -h -? --help           Print this help.

Examples
========

  python -m robot.testdoc mytestcases.html testdoc.html
  python -m robot.testdoc --name smoke_test_plan -i smoke path/to/my_tests/ doc.html
"""

import sys
import os
import codecs
import time

if 'robot' not in sys.modules:
    import pythonpathsetter   # running testdoc.py as script

from robot import utils
from robot.running import TestSuite, Keyword
from robot.conf import RobotSettings
from robot.parsing import populators
from robot.reporting.htmlfilewriter import HtmlFileWriter, ModelWriter
from robot.reporting.jsonwriter import JsonWriter

class TestDoc(utils.Application):

    def __init__(self):
        utils.Application.__init__(self, USAGE, arg_limits=(2,))

    def main(self, args, title=None, **options):
        datasources = args[0:-1]
        outfile = os.path.abspath(args[-1])
        suite = TestSuiteFactory(datasources, **options)
        self._write_test_doc(suite, outfile, title)
        self.console(outfile)

    def _write_test_doc(self, suite, outfile, title):
        output = codecs.open(outfile, 'w', 'UTF-8')
        model_writer = TestdocModelWriter(output, suite, title)
        HtmlFileWriter(output, model_writer).write('testdoc.html')
        output.close()

def TestSuiteFactory(datasources, **options):
    if isinstance(datasources, basestring):
        datasources = [datasources]
    populators.PROCESS_CURDIR = False
    try:
        return TestSuite(datasources, RobotSettings(options))
    finally:
        populators.PROCESS_CURDIR = True

class TestdocModelWriter(ModelWriter):

    def __init__(self, output, suite, title=None):
        self._output = output
        self._output_path = getattr(output, 'name', None)
        self._suite = suite
        self._title = title.replace('_', ' ') if title else ''

    def write(self, line):
        self._output.write('<script type="text/javascript">' + os.linesep)
        self.write_data()
        self._output.write('</script>' + os.linesep)

    def write_data(self):
        generated_time = time.localtime()
        model = {
            'suite': JsonConverter(self._output_path).convert(self._suite),
            'title': self._title,
            'generated': utils.format_time(generated_time, gmtsep=' '),
            'generatedMillis': long(time.mktime(generated_time) * 1000)
        }
        JsonWriter(self._output).write_json('testdoc = ', model)

class JsonConverter(object):

    def __init__(self, output_path=None):
        self._output_path = output_path

    def convert(self, suite):
        return self._convert_suite(suite)

    def _convert_suite(self, suite):
        return {
            'source': suite.source or '',
            'relativeSource': self._get_relative_source(suite.source),
            'id': suite.id,
            'name': suite.name,
            'fullName': suite.longname,
            'doc': suite.doc,
            'metadata': dict(suite.metadata),
            'numberOfTests': suite.get_test_count(),
            'suites': self._convert_suites(suite),
            'tests': self._convert_tests(suite),
            'keywords': list(self._convert_keywords(suite))
        }

    def _get_relative_source(self, source):
        if not source or not self._output_path:
            return ''
        return utils.get_link_path(source, os.path.dirname(self._output_path))

    def _convert_suites(self, suite):
        return [self._convert_suite(s) for s in suite.suites]

    def _convert_tests(self, suite):
        return [self._convert_test(t) for t in suite.tests]

    def _convert_test(self, test):
        return {
            'name': test.name,
            'fullName': test.longname,
            'id': test.id,
            'doc': test.doc,
            'tags': utils.normalize_tags(test.tags),
            'timeout': self._get_timeout(test.timeout),
            'keywords': list(self._convert_keywords(test))
        }

    def _convert_keywords(self, item):
        if item.setup.name:
            yield self._convert_keyword(item.setup, type='SETUP')
        for kw in getattr(item, 'keywords', []):
            yield self._convert_keyword(kw)
        if item.teardown.name:
            yield self._convert_keyword(item.teardown, type='TEARDOWN')

    def _convert_keyword(self, kw, type=None):
        return {
            'name': kw._get_name(kw.name) if isinstance(kw, Keyword) else kw.name,
            'arguments': ', '.join(kw.args),
            'type': type or {'kw': 'KEYWORD', 'for': 'FOR'}[kw.type]
        }

    def _get_timeout(self, timeout):
        try:
            tout = utils.secs_to_timestr(utils.timestr_to_secs(timeout.string))
        except ValueError:
            tout = timeout.string
        if timeout.message:
            tout += ' :: ' + timeout.message
        return tout

def testdoc_cli(args):
    """Executes testdoc similarly as from the command line.

    :param args: command line arguments as a list of strings.

    Example:
       testdoc_cli(['--title', 'Test Plan', 'mytests', 'plan.html'])
    """
    TestDoc().execute_cli(args)

if __name__ == '__main__':
    testdoc_cli(sys.argv[1:])
<|endoftext|>


<commit_before>VERSION = '2.0'
RELEASE = 'beta'
TIMESTAMP = '20080623-092421'
<commit_msg>fixed version<commit_after>VERSION = 'trunk'
RELEASE = '20080623'
TIMESTAMP = '20080623-135031'
<|endoftext|>


<commit_before>#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.test_framework import AuroracoinTestFramework
from test_framework.util import (
    assert_equal,
)
from test_framework.blocktools import (
    TIME_GENESIS_BLOCK,
)

class CreateTxWalletTest(AuroracoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()

    def run_test(self):
        self.log.info('Create some old blocks')
        self.nodes[0].setmocktime(TIME_GENESIS_BLOCK)
        self.nodes[0].generate(200)
        self.nodes[0].setmocktime(0)

        self.log.info('Check that we have some (old) blocks and that anti-fee-sniping is disabled')
        assert_equal(self.nodes[0].getblockchaininfo()['blocks'], 200)
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
        assert_equal(tx['locktime'], 0)

        self.log.info('Check that anti-fee-sniping is enabled when we mine a recent block')
        self.nodes[0].generate(1)
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
        assert 0 < tx['locktime'] <= 201

if __name__ == '__main__':
    CreateTxWalletTest().main()<commit_msg>Bitcoin: 0d101a340c44841cbbc5982d55354b1787bc39e2 (test: Add test for maxtxfee option).<commit_after>#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

from test_framework.test_framework import AuroracoinTestFramework
from test_framework.util import (
    assert_equal,
    assert_raises_rpc_error,
)
from test_framework.blocktools import (
    TIME_GENESIS_BLOCK,
)

class CreateTxWalletTest(AuroracoinTestFramework):
    def set_test_params(self):
        self.setup_clean_chain = True
        self.num_nodes = 1

    def skip_test_if_missing_module(self):
        self.skip_if_no_wallet()

    def run_test(self):
        self.log.info('Create some old blocks')
        self.nodes[0].setmocktime(TIME_GENESIS_BLOCK)
        self.nodes[0].generate(200)
        self.nodes[0].setmocktime(0)

        self.test_anti_fee_sniping()
        self.test_tx_size_too_large()

    def test_anti_fee_sniping(self):
        self.log.info('Check that we have some (old) blocks and that anti-fee-sniping is disabled')
        assert_equal(self.nodes[0].getblockchaininfo()['blocks'], 200)
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
        assert_equal(tx['locktime'], 0)

        self.log.info('Check that anti-fee-sniping is enabled when we mine a recent block')
        self.nodes[0].generate(1)
        txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
        tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex'])
        assert 0 < tx['locktime'] <= 201

    def test_tx_size_too_large(self):
        # More than 10kB of outputs, so that we hit -maxtxfee with a high feerate
        outputs = {self.nodes[0].getnewaddress(address_type='bech32'): 0.000025 for i in range(400)}
        raw_tx = self.nodes[0].createrawtransaction(inputs=[], outputs=outputs)

        for fee_setting in ['-minrelaytxfee=0.01', '-mintxfee=0.01', '-paytxfee=0.01']:
            self.log.info('Check maxtxfee in combination with {}'.format(fee_setting))
            self.restart_node(0, extra_args=[fee_setting])
            assert_raises_rpc_error(
                -6,
                "Fee exceeds maximum configured by -maxtxfee",
                lambda: self.nodes[0].sendmany(dummy="", amounts=outputs),
            )
            assert_raises_rpc_error(
                -4,
                "Fee exceeds maximum configured by -maxtxfee",
                lambda: self.nodes[0].fundrawtransaction(hexstring=raw_tx),
            )

        self.log.info('Check maxtxfee in combination with settxfee')
        self.restart_node(0)
        self.nodes[0].settxfee(0.01)
        assert_raises_rpc_error(
            -6,
            "Fee exceeds maximum configured by -maxtxfee",
            lambda: self.nodes[0].sendmany(dummy="", amounts=outputs),
        )
        assert_raises_rpc_error(
            -4,
            "Fee exceeds maximum configured by -maxtxfee",
            lambda: self.nodes[0].fundrawtransaction(hexstring=raw_tx),
        )
        self.nodes[0].settxfee(0)

if __name__ == '__main__':
    CreateTxWalletTest().main()<|endoftext|>


<commit_before>from PyQt4 import QtCore, QtGui
from rpc.common import Request

class RPCresponder:
    """ Handles the processing of RPC requests"""
    def __init__(self, state):
        # make all of the string functions available through
        # string.func_name
        import string
        self.string = string
        self.state = state

    def _listMethods(self):
        # implement this method so that system.listMethods
        # knows to advertise the strings methods
        return list_public_methods(self) + \
                ['string.' + method for method in list_public_methods(self.string)]

    # RPC methods
    def enq(self,rqData):
        """ Unmarshalls the request and add it to the queue"""
        # NOTE : this should be lock-secured
        print '\033[31m-acquire Responder\033[0m'
        #self.state.lock.acquire()

        rq = Request(**rqData)
        self.state.queue.append(rq)
        print 'Responder, rq:' rq

        self.state.executeOperations()
        print '\033[31m-release Responder\033[0m'
        #self.state.lock.release()
        return True
<commit_msg>print responder<commit_after>from PyQt4 import QtCore, QtGui
from rpc.common import Request

class RPCresponder:
    """ Handles the processing of RPC requests"""
    def __init__(self, state):
        # make all of the string functions available through
        # string.func_name
        import string
        self.string = string
        self.state = state

    def _listMethods(self):
        # implement this method so that system.listMethods
        # knows to advertise the strings methods
        return list_public_methods(self) + \
                ['string.' + method for method in list_public_methods(self.string)]

    # RPC methods
    def enq(self,rqData):
        """ Unmarshalls the request and add it to the queue"""
        # NOTE : this should be lock-secured
        print '\033[31m-acquire Responder\033[0m'
        #self.state.lock.acquire()

        rq = Request(**rqData)
        self.state.queue.append(rq)
        print 'Responder, rq:', rq

        self.state.executeOperations()
        print '\033[31m-release Responder\033[0m'
        #self.state.lock.release()
        return True
<|endoftext|>