Philipp Hörist pushed to branch master at gajim / gajim
Commits:
91ebe373 by Philipp Hörist at 2018-11-27T20:04:13Z
AccountsWindow: Fix back button
- - - - -
1 changed file:
- gajim/gtk/accounts.py
Changes:
=====================================
gajim/gtk/accounts.py
=====================================
@@ -80,6 +80,10 @@ class AccountsWindow(Gtk.ApplicationWindow):
app.ged.register_event_handler(
'our-show', ged.GUI2, self._nec_our_status)
+ @property
+ def stack(self):
+ return self._ui.stack
+
def _nec_our_status(self, event):
self.update_accounts()
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/91ebe37359419c97f1a0c995c1e9e62a3b…
--
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/91ebe37359419c97f1a0c995c1e9e62a3b…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / python-nbxmpp
Commits:
07355321 by Philipp Hörist at 2018-11-27T19:16:24Z
Dont inherit from object
This is only needed for python2 compatibility
- - - - -
10 changed files:
- nbxmpp/bosh.py
- nbxmpp/client_nb.py
- nbxmpp/dispatcher_nb.py
- nbxmpp/idlequeue.py
- nbxmpp/plugin.py
- nbxmpp/protocol.py
- nbxmpp/proxy_connectors.py
- nbxmpp/simplexml.py
- nbxmpp/stringprepare.py
- nbxmpp/tls_nb.py
Changes:
=====================================
nbxmpp/bosh.py
=====================================
@@ -493,7 +493,7 @@ def get_rand_number():
return int(binascii.hexlify(os.urandom(6)), 16)
-class AckChecker(object):
+class AckChecker:
"""
Class for generating rids and generating and checking acknowledgements in
BOSH messages
@@ -536,7 +536,7 @@ class AckChecker(object):
return self.rid
-class KeyStack(object):
+class KeyStack:
"""
Class implementing key sequences for BOSH messages
"""
=====================================
nbxmpp/client_nb.py
=====================================
@@ -34,7 +34,7 @@ from .const import Event
log = logging.getLogger('nbxmpp.client_nb')
-class NonBlockingClient(object):
+class NonBlockingClient:
"""
Client class is XMPP connection mountpoint. Objects for authentication,
network communication, roster, xml parsing ... are plugged to client object.
=====================================
nbxmpp/dispatcher_nb.py
=====================================
@@ -41,7 +41,7 @@ DEFAULT_TIMEOUT_SECONDS = 25
XML_DECLARATION = '<?xml version=\'1.0\'?>'
# FIXME: ugly
-class Dispatcher(object):
+class Dispatcher:
"""
Why is this here - I needed to redefine Dispatcher for BOSH and easiest way
was to inherit original Dispatcher (now renamed to XMPPDispatcher). Trouble
=====================================
nbxmpp/idlequeue.py
=====================================
@@ -63,7 +63,7 @@ def get_idlequeue():
return SelectIdleQueue()
-class IdleObject(object):
+class IdleObject:
"""
Idle listener interface. Listed methods are called by IdleQueue.
"""
@@ -203,7 +203,7 @@ class IdleCommand(IdleObject):
self._return_result()
-class IdleQueue(object):
+class IdleQueue:
"""
IdleQueue provide three distinct time based features. Uses select.poll()
=====================================
nbxmpp/plugin.py
=====================================
@@ -20,7 +20,7 @@ import logging
log = logging.getLogger('nbxmpp.plugin')
-class PlugIn(object):
+class PlugIn:
"""
Abstract xmpppy plugin infrastructure code, providing plugging in/out and
debugging functionality
=====================================
nbxmpp/protocol.py
=====================================
@@ -638,7 +638,7 @@ stream_exceptions = {'bad-format': BadFormat,
'xml-not-well-formed': XMLNotWellFormed}
-class JID(object):
+class JID:
"""
JID can be built from string, modified, compared, serialised into string
"""
=====================================
nbxmpp/proxy_connectors.py
=====================================
@@ -30,7 +30,7 @@ from base64 import b64encode
log = logging.getLogger('nbxmpp.proxy_connectors')
-class ProxyConnector(object):
+class ProxyConnector:
"""
Interface for proxy-connecting object - when tunnneling XMPP over proxies,
some connecting process usually has to be done before opening stream. Proxy
=====================================
nbxmpp/simplexml.py
=====================================
@@ -32,7 +32,7 @@ def XMLescape(txt):
# replace also FORM FEED and ESC, because they are not valid XML chars
return txt.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace('\x0C', "").replace('\x1B', "")
-class Node(object):
+class Node:
"""
Node class describes syntax of separate XML Node. It have a constructor that
permits node creation from set of "namespace name", attributes and payload
@@ -471,7 +471,7 @@ class Node(object):
raise AttributeError
-class T(object):
+class T:
"""
Auxiliary class used to quick access to node's child nodes
"""
@@ -506,7 +506,7 @@ class NT(T):
return self.node.addChild(attr, payload=[val])
-class NodeBuilder(object):
+class NodeBuilder:
"""
Builds a Node class minidom from data parsed to it. This class used for two
purposes:
=====================================
nbxmpp/stringprepare.py
=====================================
@@ -26,7 +26,7 @@ import unicodedata
from encodings import idna
-class ILookupTable(object):
+class ILookupTable:
"""
Interface for character lookup classes
"""
@@ -38,7 +38,7 @@ class ILookupTable(object):
pass
-class IMappingTable(object):
+class IMappingTable:
"""
Interface for character mapping classes
"""
@@ -50,14 +50,14 @@ class IMappingTable(object):
pass
-class LookupTableFromFunction(object):
+class LookupTableFromFunction:
__implements__ = ILookupTable
def __init__(self, in_table_function):
self.lookup = in_table_function
-class LookupTable(object):
+class LookupTable:
__implements__ = ILookupTable
def __init__(self, table):
@@ -67,14 +67,14 @@ class LookupTable(object):
return c in self._table
-class MappingTableFromFunction(object):
+class MappingTableFromFunction:
__implements__ = IMappingTable
def __init__(self, map_table_function):
self.map = map_table_function
-class EmptyMappingTable(object):
+class EmptyMappingTable:
__implements__ = IMappingTable
def __init__(self, in_table_function):
@@ -87,7 +87,7 @@ class EmptyMappingTable(object):
return c
-class Profile(object):
+class Profile:
def __init__(self, mappings=None, normalize=True, prohibiteds=None,
check_unassigneds=True, check_bidi=True):
if mappings is None:
@@ -161,7 +161,7 @@ class Profile(object):
raise UnicodeError("Violation of BIDI Requirement 3")
-class NamePrep(object):
+class NamePrep:
"""
Implements preparation of internationalized domain names
=====================================
nbxmpp/tls_nb.py
=====================================
@@ -52,7 +52,7 @@ def gattr(obj, attr, default=None):
return default
-class SSLWrapper(object):
+class SSLWrapper:
"""
Abstract SSLWrapper base class
"""
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/commit/073553215d153ff1f3991a2234…
--
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/commit/073553215d153ff1f3991a2234…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / python-nbxmpp
Commits:
43e0a537 by André Apitzsch at 2018-11-26T22:46:24Z
Replace ustr() by str()
- - - - -
2c7a3e2c by Philipp Hörist at 2018-11-27T19:11:33Z
Merge branch 'ustr' into 'master'
Replace ustr() by str()
See merge request gajim/python-nbxmpp!22
- - - - -
3 changed files:
- nbxmpp/c14n.py
- nbxmpp/simplexml.py
- nbxmpp/transports_nb.py
Changes:
=====================================
nbxmpp/c14n.py
=====================================
@@ -22,8 +22,6 @@
XML canonicalisation methods (for XEP-0116)
"""
-from .simplexml import ustr
-
def c14n(node, is_buggy):
s = "<" + node.name
if node.namespace:
@@ -34,7 +32,7 @@ def c14n(node, is_buggy):
for key in sorted_attrs:
if not is_buggy and key == 'xmlns':
continue
- val = ustr(node.attrs[key])
+ val = str(node.attrs[key])
# like XMLescape() but with whitespace and without >
s += ' %s="%s"' % (key, normalise_attr(val))
s += ">"
=====================================
nbxmpp/simplexml.py
=====================================
@@ -32,23 +32,6 @@ def XMLescape(txt):
# replace also FORM FEED and ESC, because they are not valid XML chars
return txt.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace('\x0C', "").replace('\x1B', "")
-ENCODING='utf-8'
-
-def ustr(what):
- """
- Converts object "what" to unicode string using it's own __str__ method if
- accessible or unicode method otherwise
- """
- if isinstance(what, str):
- return what
- try:
- r = what.__str__()
- except AttributeError:
- r = str(what)
- if not isinstance(r, str):
- return str(r, ENCODING)
- return r
-
class Node(object):
"""
Node class describes syntax of separate XML Node. It have a constructor that
@@ -134,7 +117,7 @@ class Node(object):
if isinstance(i, Node):
self.addChild(node=i)
else:
- self.data.append(ustr(i))
+ self.data.append(str(i))
def lookup_nsp(self, pfx=''):
ns = self.nsd.get(pfx, None)
@@ -159,7 +142,7 @@ class Node(object):
if 'xmlns' not in self.attrs:
s += ' xmlns="%s"' % self.namespace
for key in self.attrs.keys():
- val = ustr(self.attrs[key])
+ val = str(self.attrs[key])
s += ' %s="%s"' % (key, XMLescape(val))
s += ">"
@@ -218,7 +201,7 @@ class Node(object):
"""
Add some CDATA to node
"""
- self.data.append(ustr(data))
+ self.data.append(str(data))
def clearData(self):
"""
@@ -379,7 +362,7 @@ class Node(object):
"""
Set node's CDATA to provided string. Resets all previous CDATA!
"""
- self.data = [ustr(data)]
+ self.data = [str(data)]
def setName(self, val):
"""
@@ -441,9 +424,9 @@ class Node(object):
(optionally) attributes "attrs" and sets it's CDATA to string "val"
"""
try:
- self.getTag(tag, attrs).setData(ustr(val))
+ self.getTag(tag, attrs).setData(str(val))
except Exception:
- self.addChild(tag, attrs, payload = [ustr(val)])
+ self.addChild(tag, attrs, payload = [str(val)])
def has_attr(self, key):
"""
=====================================
nbxmpp/transports_nb.py
=====================================
@@ -38,7 +38,6 @@ try:
except ImportError:
from urlparse import urlparse
-from .simplexml import ustr
from .plugin import PlugIn
from .idlequeue import IdleObject
from . import proxy_connectors
@@ -544,7 +543,7 @@ class NonBlockingTCP(NonBlockingTransport, IdleObject):
if isinstance(stanza, str):
stanza = stanza.encode('utf-8')
elif not isinstance(stanza, str):
- stanza = ustr(stanza).encode('utf-8')
+ stanza = str(stanza).encode('utf-8')
return stanza
def _plug_idle(self, writable, readable):
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/compare/397382139300c7b992934c6c3…
--
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/compare/397382139300c7b992934c6c3…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / gajim
Commits:
f1ab9fb6 by Philipp Hörist at 2018-11-27T18:23:34Z
Fix connection resume
Fixes #9458
- - - - -
1 changed file:
- gajim/common/connection.py
Changes:
=====================================
gajim/common/connection.py
=====================================
@@ -670,7 +670,7 @@ class Connection(CommonConnection, ConnectionHandlers):
self.old_show = app.SHOW_LIST[self.connected]
self.connected = 0
if not self.on_purpose:
- if not self.connection.resume_supported:
+ if not self._sm_resume_data:
app.nec.push_incoming_event(OurShowEvent(None, conn=self,
show='offline'))
else:
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/f1ab9fb6838f2a8a36370e404937c746b0…
--
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/f1ab9fb6838f2a8a36370e404937c746b0…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / python-nbxmpp
Commits:
39738213 by Philipp Hörist at 2018-11-27T17:52:42Z
Fix sm resume
- - - - -
2 changed files:
- nbxmpp/client_nb.py
- nbxmpp/smacks.py
Changes:
=====================================
nbxmpp/client_nb.py
=====================================
@@ -586,10 +586,9 @@ class NonBlockingClient(object):
elif self.SASL.startsasl == 'success':
self.connected += '+sasl'
self.Dispatcher.Event(Realm.CONNECTING, Event.AUTH_SUCCESSFUL)
+ self._owner.Smacks.register_handlers()
def bind(self):
- self._owner.Smacks.register_handlers()
-
# Check if we can resume
if self._owner.Smacks.resume_supported:
self._owner.Smacks.resume_request()
=====================================
nbxmpp/smacks.py
=====================================
@@ -279,7 +279,7 @@ class Smacks(PlugIn):
self._owner.Dispatcher.Event(Realm.CONNECTING, Event.RESUME_FAILED)
# We failed while resuming
self.resume_supported = False
- self._owner.start_bind()
+ self._owner.bind()
self._reset_state()
def _reset_state(self):
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/commit/397382139300c7b992934c6c3e…
--
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/commit/397382139300c7b992934c6c3e…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / gajim
Commits:
f942e2c7 by Andrey Gursky at 2018-11-27T01:17:25Z
Fix receipts for chat
This is a regression from e3050697
- - - - -
1 changed file:
- gajim/common/modules/receipts.py
Changes:
=====================================
gajim/common/modules/receipts.py
=====================================
@@ -78,7 +78,7 @@ class Receipts:
event.resource)
contact = app.contacts.get_contact(self._account, event.jid)
- if contact is None and contact.sub not in ('to', 'none'):
+ if contact is not None and contact.sub not in ('to', 'none'):
return contact
@staticmethod
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/f942e2c70faf2229a59a24b8293712ac79…
--
View it on GitLab: https://dev.gajim.org/gajim/gajim/commit/f942e2c70faf2229a59a24b8293712ac79…
You're receiving this email because of your account on dev.gajim.org.
Philipp Hörist pushed to branch master at gajim / python-nbxmpp
Commits:
fabdaa4e by André Apitzsch at 2018-11-25T13:16:55Z
Test: Use Mock from standard library
- - - - -
02604951 by Philipp Hörist at 2018-11-25T18:49:54Z
Merge branch 'mock' into 'master'
Test: Use Mock from standard library
See merge request gajim/python-nbxmpp!20
- - - - -
5 changed files:
- test/broken/test_xmpp_smacks.py
- − test/lib/mock.py
- test/lib/xmpp_mocks.py
- test/unit/test_xmpp_client_nb.py
- test/unit/test_xmpp_dispatcher_nb.py
Changes:
=====================================
test/broken/test_xmpp_smacks.py
=====================================
@@ -18,7 +18,6 @@ class TestDispatcherNB(unittest.TestCase):
# Setup mock client
self.client = Mock()
- self.client._caller = Mock()
self.client.defaultNamespace = protocol.NS_CLIENT
self.client.Connection = Mock() # mock transport
self.con = self.client.Connection
=====================================
test/lib/mock.py deleted
=====================================
@@ -1,463 +0,0 @@
-#
-# (c) Dave Kirby 2001 - 2005
-# mock(a)thedeveloperscoach.com
-#
-# Original call interceptor and call assertion code by Phil Dawes (pdawes(a)users.sourceforge.net)
-# Call interceptor code enhanced by Bruce Cropley (cropleyb(a)yahoo.com.au)
-#
-# This Python module and associated files are released under the FreeBSD
-# license. Essentially, you can do what you like with it except pretend you wrote
-# it yourself.
-#
-#
-# Copyright (c) 2005, Dave Kirby
-# Copyright (c) 2009, Yann Leboulanger
-#
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# * Neither the name of this library nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# mock(a)thedeveloperscoach.com
-
-
-"""
-Mock object library for Python. Mock objects can be used when unit testing
-to remove a dependency on another production class. They are typically used
-when the dependency would either pull in lots of other classes, or
-significantly slow down the execution of the test.
-They are also used to create exceptional conditions that cannot otherwise
-be easily triggered in the class under test.
-"""
-
-__version__ = "0.1.0"
-
-# Added in Python 2.1
-import inspect
-import re
-
-class MockInterfaceError(Exception):
- pass
-
-class Mock(object):
- """
- The Mock class emulates any other class for testing purposes.
- All method calls are stored for later examination.
- """
-
- def __init__(self, returnValues=None, realClass=None):
- """
- The Mock class constructor takes a dictionary of method names and
- the values they return. Methods that are not in the returnValues
- dictionary will return None.
- You may also supply a class whose interface is being mocked.
- All calls will be checked to see if they appear in the original
- interface. Any calls to methods not appearing in the real class
- will raise a MockInterfaceError. Any calls that would fail due to
- non-matching parameter lists will also raise a MockInterfaceError.
- Both of these help to prevent the Mock class getting out of sync
- with the class it is Mocking.
- """
- self.mockCalledMethods = {}
- self.mockAllCalledMethods = []
- self.mockReturnValues = returnValues or {}
- self.mockExpectations = {}
- self.realClass = realClass
- self.realClassMethods = None
- if realClass:
- self.realClassMethods = dict(inspect.getmembers(realClass, inspect.isroutine))
- for retMethod in self.mockReturnValues.keys():
- if retMethod not in self.realClassMethods:
- raise MockInterfaceError("Return value supplied for method '%s' that was not in the original class" % retMethod)
- self._setupSubclassMethodInterceptors()
-
- def _setupSubclassMethodInterceptors(self):
- methods = inspect.getmembers(self.realClass, inspect.isroutine)
- baseMethods = dict(inspect.getmembers(Mock, inspect.ismethod))
- for m in methods:
- name = m[0]
- # Don't record calls to methods of Mock base class.
- if not name in baseMethods:
- self.__dict__[name] = MockCallable(name, self, handcrafted=True)
-
- def __getattr__(self, name):
- return MockCallable(name, self)
-
- def mockAddReturnValues(self, **methodReturnValues ):
- self.mockReturnValues.update(methodReturnValues)
-
- def mockSetExpectation(self, name, testFn, after=0, until=0):
- self.mockExpectations.setdefault(name, []).append((testFn, after, until))
-
- def _checkInterfaceCall(self, name, callParams, callKwParams):
- """
- Check that a call to a method of the given name to the original
- class with the given parameters would not fail. If it would fail,
- raise a MockInterfaceError.
- Based on the Python 2.3.3 Reference Manual section 5.3.4: Calls.
- """
- if self.realClassMethods is None:
- return
- if name not in self.realClassMethods:
- return
-
- func = self.realClassMethods[name]
- try:
- args, varargs, varkw, defaults = inspect.getargspec(func)
- except TypeError:
- # func is not a Python function. It is probably a builtin,
- # such as __repr__ or __coerce__. TODO: Checking?
- # For now assume params are OK.
- return
-
- # callParams doesn't include self; args does include self.
- numPosCallParams = 1 + len(callParams)
-
- if numPosCallParams > len(args) and not varargs:
- raise MockInterfaceError("Original %s() takes at most %s arguments (%s given)" %
- (name, len(args), numPosCallParams))
-
- # Get the number of positional arguments that appear in the call,
- # also check for duplicate parameters and unknown parameters
- numPosSeen = _getNumPosSeenAndCheck(numPosCallParams, callKwParams, args, varkw)
-
- lenArgsNoDefaults = len(args) - len(defaults or [])
- if numPosSeen < lenArgsNoDefaults:
- raise MockInterfaceError("Original %s() takes at least %s arguments (%s given)" % (name, lenArgsNoDefaults, numPosSeen))
-
- def mockGetAllCalls(self):
- """
- Return a list of MockCall objects,
- representing all the methods in the order they were called.
- """
- return self.mockAllCalledMethods
- getAllCalls = mockGetAllCalls # deprecated - kept for backward compatibility
-
- def mockGetNamedCalls(self, methodName):
- """
- Return a list of MockCall objects,
- representing all the calls to the named method in the order they were called.
- """
- return self.mockCalledMethods.get(methodName, [])
- getNamedCalls = mockGetNamedCalls # deprecated - kept for backward compatibility
-
- def mockCheckCall(self, index, name, *args, **kwargs):
- '''test that the index-th call had the specified name and parameters'''
- call = self.mockAllCalledMethods[index]
- assert name == call.getName(), "%r != %r" % (name, call.getName())
- call.checkArgs(*args, **kwargs)
-
-
-def _getNumPosSeenAndCheck(numPosCallParams, callKwParams, args, varkw):
- """
- Positional arguments can appear as call parameters either named as
- a named (keyword) parameter, or just as a value to be matched by
- position. Count the positional arguments that are given by either
- keyword or position, and check for duplicate specifications.
- Also check for arguments specified by keyword that do not appear
- in the method's parameter list.
- """
- posSeen = {}
- for arg in args[:numPosCallParams]:
- posSeen[arg] = True
- for kwp in callKwParams:
- if kwp in posSeen:
- raise MockInterfaceError("%s appears as both a positional and named parameter." % kwp)
- if kwp in args:
- posSeen[kwp] = True
- elif not varkw:
- raise MockInterfaceError("Original method does not have a parameter '%s'" % kwp)
- return len(posSeen)
-
-class MockCall:
- """
- MockCall records the name and parameters of a call to an instance
- of a Mock class. Instances of MockCall are created by the Mock class,
- but can be inspected later as part of the test.
- """
- def __init__(self, name, params, kwparams ):
- self.name = name
- self.params = params
- self.kwparams = kwparams
-
- def checkArgs(self, *args, **kwargs):
- assert args == self.params, "%r != %r" % (args, self.params)
- assert kwargs == self.kwparams, "%r != %r" % (kwargs, self.kwparams)
-
- def getParam( self, n ):
- if isinstance(n, int):
- return self.params[n]
- elif isinstance(n, str):
- return self.kwparams[n]
- else:
- raise IndexError('illegal index type for getParam')
-
- def getNumParams(self):
- return len(self.params)
-
- def getNumKwParams(self):
- return len(self.kwparams)
-
- def getName(self):
- return self.name
-
- #pretty-print the method call
- def __str__(self):
- s = self.name + "("
- sep = ''
- for p in self.params:
- s = s + sep + repr(p)
- sep = ', '
- items = sorted(self.kwparams.items())
- for k, v in items:
- s = s + sep + k + '=' + repr(v)
- sep = ', '
- s = s + ')'
- return s
- def __repr__(self):
- return self.__str__()
-
-class MockCallable:
- """
- Intercepts the call and records it, then delegates to either the mock's
- dictionary of mock return values that was passed in to the constructor,
- or a handcrafted method of a Mock subclass.
- """
- def __init__(self, name, mock, handcrafted=False):
- self.name = name
- self.mock = mock
- self.handcrafted = handcrafted
-
- def __call__(self, *params, **kwparams):
- self.mock._checkInterfaceCall(self.name, params, kwparams)
- thisCall = self.recordCall(params, kwparams)
- self.checkExpectations(thisCall, params, kwparams)
- return self.makeCall(params, kwparams)
-
- def recordCall(self, params, kwparams):
- """
- Record the MockCall in an ordered list of all calls, and an ordered
- list of calls for that method name.
- """
- thisCall = MockCall(self.name, params, kwparams)
- calls = self.mock.mockCalledMethods.setdefault(self.name, [])
- calls.append(thisCall)
- self.mock.mockAllCalledMethods.append(thisCall)
- return thisCall
-
- def makeCall(self, params, kwparams):
- if self.handcrafted:
- allPosParams = (self.mock,) + params
- func = _findFunc(self.mock.realClass, self.name)
- if not func:
- raise NotImplementedError
- return func(*allPosParams, **kwparams)
- else:
- returnVal = self.mock.mockReturnValues.get(self.name)
- if isinstance(returnVal, ReturnValuesBase):
- returnVal = returnVal.next()
- return returnVal
-
- def checkExpectations(self, thisCall, params, kwparams):
- if self.name in self.mock.mockExpectations:
- callsMade = len(self.mock.mockCalledMethods[self.name])
- for (expectation, after, until) in self.mock.mockExpectations[self.name]:
- if callsMade > after and (until==0 or callsMade < until):
- assert expectation(self.mock, thisCall, len(self.mock.mockAllCalledMethods)-1), 'Expectation failed: '+str(thisCall)
-
-
-def _findFunc(cl, name):
- """ Depth first search for a method with a given name. """
- if name in cl.__dict__:
- return cl.__dict__[name]
- for base in cl.__bases__:
- func = _findFunc(base, name)
- if func:
- return func
- return None
-
-
-
-class ReturnValuesBase:
- def next(self):
- try:
- return self.iter.next()
- except StopIteration:
- raise AssertionError("No more return values")
- def __iter__(self):
- return self
-
-class ReturnValues(ReturnValuesBase):
- def __init__(self, *values):
- self.iter = iter(values)
-
-
-class ReturnIterator(ReturnValuesBase):
- def __init__(self, iterator):
- self.iter = iter(iterator)
-
-
-def expectParams(*params, **keywords):
- '''check that the callObj is called with specified params and keywords
- '''
- def fn(mockObj, callObj, idx):
- return callObj.params == params and callObj.kwparams == keywords
- return fn
-
-
-def expectAfter(*methods):
- '''check that the function is only called after all the functions in 'methods'
- '''
- def fn(mockObj, callObj, idx):
- calledMethods = [method.getName() for method in mockObj.mockGetAllCalls()]
- #skip last entry, since that is the current call
- calledMethods = calledMethods[:-1]
- for method in methods:
- if method not in calledMethods:
- return False
- return True
- return fn
-
-def expectException(exception, *args, **kwargs):
- ''' raise an exception when the method is called
- '''
- def fn(mockObj, callObj, idx):
- raise exception(*args, **kwargs)
- return fn
-
-
-def expectParam(paramIdx, cond):
- '''check that the callObj is called with parameter specified by paramIdx (a position index or keyword)
- fulfills the condition specified by cond.
- cond is a function that takes a single argument, the value to test.
- '''
- def fn(mockObj, callObj, idx):
- param = callObj.getParam(paramIdx)
- return cond(param)
- return fn
-
-def EQ(value):
- def testFn(param):
- return param == value
- return testFn
-
-def NE(value):
- def testFn(param):
- return param != value
- return testFn
-
-def GT(value):
- def testFn(param):
- return param > value
- return testFn
-
-def LT(value):
- def testFn(param):
- return param < value
- return testFn
-
-def GE(value):
- def testFn(param):
- return param >= value
- return testFn
-
-def LE(value):
- def testFn(param):
- return param <= value
- return testFn
-
-def AND(*condlist):
- def testFn(param):
- for cond in condlist:
- if not cond(param):
- return False
- return True
- return testFn
-
-def OR(*condlist):
- def testFn(param):
- for cond in condlist:
- if cond(param):
- return True
- return False
- return testFn
-
-def NOT(cond):
- def testFn(param):
- return not cond(param)
- return testFn
-
-def MATCHES(regex, *args, **kwargs):
- compiled_regex = re.compile(regex, *args, **kwargs)
- def testFn(param):
- return compiled_regex.match(param) is not None
- return testFn
-
-def SEQ(*sequence):
- iterator = iter(sequence)
- def testFn(param):
- try:
- cond = iterator.next()
- except StopIteration:
- raise AssertionError('SEQ exhausted')
- return cond(param)
- return testFn
-
-def IS(instance):
- def testFn(param):
- return param is instance
- return testFn
-
-def ISINSTANCE(class_):
- def testFn(param):
- return isinstance(param, class_)
- return testFn
-
-def ISSUBCLASS(class_):
- def testFn(param):
- return issubclass(param, class_)
- return testFn
-
-def CONTAINS(val):
- def testFn(param):
- return val in param
- return testFn
-
-def IN(container):
- def testFn(param):
- return param in container
- return testFn
-
-def HASATTR(attr):
- def testFn(param):
- return hasattr(param, attr)
- return testFn
-
-def HASMETHOD(method):
- def testFn(param):
- return hasattr(param, method) and callable(getattr(param, method))
- return testFn
-
-CALLABLE = callable
=====================================
test/lib/xmpp_mocks.py
=====================================
@@ -4,7 +4,7 @@ Module with dummy classes for unit testing of XMPP and related code.
import threading, time
-from test.lib.mock import Mock
+from unittest.mock import Mock
from nbxmpp import idlequeue
=====================================
test/unit/test_xmpp_client_nb.py
=====================================
@@ -5,9 +5,10 @@ It actually connects to a xmpp server.
'''
import unittest
+from unittest.mock import Mock
from test.lib.xmpp_mocks import MockConnection, IdleQueueThread
-from test.lib.mock import Mock
+
from nbxmpp import client_nb
# (XMPP server hostname, c2s port). Script will connect to the machine.
@@ -56,7 +57,7 @@ class TestNonBlockingClient(unittest.TestCase):
self.client = client_nb.NonBlockingClient(
domain=server_port[0],
idlequeue=self.idlequeue_thread.iq,
- caller=Mock(realClass=TempConnection))
+ caller=Mock(spec=TempConnection))
self.client.connect(
hostname=server_port[0],
=====================================
test/unit/test_xmpp_dispatcher_nb.py
=====================================
@@ -19,7 +19,6 @@ class TestDispatcherNB(unittest.TestCase):
# Setup mock client
self.client = Mock()
- self.client._caller = Mock()
self.client.defaultNamespace = protocol.NS_CLIENT
self.client.Connection = Mock() # mock transport
self.con = self.client.Connection
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/compare/633e0dd25ec69f63924d6d508…
--
View it on GitLab: https://dev.gajim.org/gajim/python-nbxmpp/compare/633e0dd25ec69f63924d6d508…
You're receiving this email because of your account on dev.gajim.org.