refactoring: renamed sat package to libervia.backend
This commit is contained in:
parent
a15648d682
commit
d2685ba11b
19 changed files with 1293 additions and 1293 deletions
0
libervia/backend/test/__init__.py
Normal file
0
libervia/backend/test/__init__.py
Normal file
58
libervia/backend/test/constants.py
Normal file
58
libervia/backend/test/constants.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# Primitivus: a SAT frontend
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from libervia.backend.core.i18n import _, D_
|
||||
from twisted.words.protocols.jabber import jid
|
||||
|
||||
|
||||
class Const(object):
|
||||
|
||||
PROF_KEY_NONE = "@NONE@"
|
||||
|
||||
PROFILE = [
|
||||
"test_profile",
|
||||
"test_profile2",
|
||||
"test_profile3",
|
||||
"test_profile4",
|
||||
"test_profile5",
|
||||
]
|
||||
JID_STR = [
|
||||
"test@example.org/SàT",
|
||||
"sender@example.net/house",
|
||||
"sender@example.net/work",
|
||||
"sender@server.net/res",
|
||||
"xxx@server.net/res",
|
||||
]
|
||||
JID = [jid.JID(jid_s) for jid_s in JID_STR]
|
||||
|
||||
PROFILE_DICT = {}
|
||||
for i in range(0, len(PROFILE)):
|
||||
PROFILE_DICT[PROFILE[i]] = JID[i]
|
||||
|
||||
MUC_STR = ["room@chat.server.domain", "sat_game@chat.server.domain"]
|
||||
MUC = [jid.JID(jid_s) for jid_s in MUC_STR]
|
||||
|
||||
NO_SECURITY_LIMIT = -1
|
||||
SECURITY_LIMIT = 0
|
||||
|
||||
# To test frontend parameters
|
||||
APP_NAME = "dummy_frontend"
|
||||
COMPOSITION_KEY = D_("Composition")
|
||||
ENABLE_UNIBOX_PARAM = D_("Enable unibox")
|
||||
PARAM_IN_QUOTES = D_("'Wysiwyg' edition")
|
||||
482
libervia/backend/test/helpers.py
Normal file
482
libervia/backend/test/helpers.py
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
## logging configuration for tests ##
|
||||
from libervia.backend.core import log_config
|
||||
log_config.sat_configure()
|
||||
|
||||
import logging
|
||||
from libervia.backend.core.log import getLogger
|
||||
getLogger().setLevel(logging.WARNING) # put this to DEBUG when needed
|
||||
|
||||
from libervia.backend.core import exceptions
|
||||
from libervia.backend.tools import config as tools_config
|
||||
from .constants import Const as C
|
||||
from wokkel.xmppim import RosterItem
|
||||
from wokkel.generic import parseXml
|
||||
from libervia.backend.core.xmpp import SatRosterProtocol
|
||||
from libervia.backend.memory.memory import Params, Memory
|
||||
from twisted.trial.unittest import FailTest
|
||||
from twisted.trial import unittest
|
||||
from twisted.internet import defer
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from twisted.words.xish import domish
|
||||
from xml.etree import cElementTree as etree
|
||||
from collections import Counter
|
||||
import re
|
||||
|
||||
|
||||
def b2s(value):
|
||||
"""Convert a bool to a unicode string used in bridge
|
||||
@param value: boolean value
|
||||
@return: unicode conversion, according to bridge convention
|
||||
|
||||
"""
|
||||
return "True" if value else "False"
|
||||
|
||||
|
||||
def mute_logging():
|
||||
"""Temporarily set the logging level to CRITICAL to not pollute the output with expected errors."""
|
||||
logger = getLogger()
|
||||
logger.original_level = logger.getEffectiveLevel()
|
||||
logger.setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
def unmute_logging():
|
||||
"""Restore the logging level after it has been temporarily disabled."""
|
||||
logger = getLogger()
|
||||
logger.setLevel(logger.original_level)
|
||||
|
||||
|
||||
class DifferentArgsException(FailTest):
|
||||
pass
|
||||
|
||||
|
||||
class DifferentXMLException(FailTest):
|
||||
pass
|
||||
|
||||
|
||||
class DifferentListException(FailTest):
|
||||
pass
|
||||
|
||||
|
||||
class FakeSAT(object):
|
||||
"""Class to simulate a SAT instance"""
|
||||
|
||||
def __init__(self):
|
||||
self.bridge = FakeBridge()
|
||||
self.memory = FakeMemory(self)
|
||||
self.trigger = FakeTriggerManager()
|
||||
self.profiles = {}
|
||||
self.reinit()
|
||||
|
||||
def reinit(self):
|
||||
"""This can be called by tests that check for sent and stored messages,
|
||||
uses FakeClient or get/set some other data that need to be cleaned"""
|
||||
for profile in self.profiles:
|
||||
self.profiles[profile].reinit()
|
||||
self.memory.reinit()
|
||||
self.stored_messages = []
|
||||
self.plugins = {}
|
||||
self.profiles = {}
|
||||
|
||||
def contact_del(self, to, profile_key):
|
||||
#TODO
|
||||
pass
|
||||
|
||||
def register_callback(self, callback, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def message_send(self, to_s, msg, subject=None, mess_type='auto', extra={}, profile_key='@NONE@'):
|
||||
self.send_and_store_message({"to": JID(to_s)})
|
||||
|
||||
def _send_message_to_stream(self, mess_data, client):
|
||||
"""Save the information to check later to whom messages have been sent.
|
||||
|
||||
@param mess_data: message data dictionnary
|
||||
@param client: profile's client
|
||||
"""
|
||||
client.xmlstream.send(mess_data['xml'])
|
||||
return mess_data
|
||||
|
||||
def _store_message(self, mess_data, client):
|
||||
"""Save the information to check later if entries have been added to the history.
|
||||
|
||||
@param mess_data: message data dictionnary
|
||||
@param client: profile's client
|
||||
"""
|
||||
self.stored_messages.append(mess_data["to"])
|
||||
return mess_data
|
||||
|
||||
def send_message_to_bridge(self, mess_data, client):
|
||||
"""Simulate the message being sent to the frontends.
|
||||
|
||||
@param mess_data: message data dictionnary
|
||||
@param client: profile's client
|
||||
"""
|
||||
return mess_data # TODO
|
||||
|
||||
def get_profile_name(self, profile_key):
|
||||
"""Get the profile name from the profile_key"""
|
||||
return profile_key
|
||||
|
||||
def get_client(self, profile_key):
|
||||
"""Convenient method to get client from profile key
|
||||
@return: client or None if it doesn't exist"""
|
||||
profile = self.memory.get_profile_name(profile_key)
|
||||
if not profile:
|
||||
raise exceptions.ProfileKeyUnknown
|
||||
if profile not in self.profiles:
|
||||
self.profiles[profile] = FakeClient(self, profile)
|
||||
return self.profiles[profile]
|
||||
|
||||
def get_jid_n_stream(self, profile_key):
|
||||
"""Convenient method to get jid and stream from profile key
|
||||
@return: tuple (jid, xmlstream) from profile, can be None"""
|
||||
return (C.PROFILE_DICT[profile_key], None)
|
||||
|
||||
def is_connected(self, profile):
|
||||
return True
|
||||
|
||||
def get_sent_messages(self, profile_index):
|
||||
"""Return all the sent messages (in the order they have been sent) and
|
||||
empty the list. Called by tests. FakeClient instances associated to each
|
||||
profile must have been previously initialized with the method
|
||||
FakeSAT.get_client.
|
||||
|
||||
@param profile_index: index of the profile to consider (cf. C.PROFILE)
|
||||
@return: the sent messages for given profile, or None"""
|
||||
try:
|
||||
tmp = self.profiles[C.PROFILE[profile_index]].xmlstream.sent
|
||||
self.profiles[C.PROFILE[profile_index]].xmlstream.sent = []
|
||||
return tmp
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
def get_sent_message(self, profile_index):
|
||||
"""Pop and return the sent message in first position (works like a FIFO).
|
||||
Called by tests. FakeClient instances associated to each profile must have
|
||||
been previously initialized with the method FakeSAT.get_client.
|
||||
|
||||
@param profile_index: index of the profile to consider (cf. C.PROFILE)
|
||||
@return: the sent message for given profile, or None"""
|
||||
try:
|
||||
return self.profiles[C.PROFILE[profile_index]].xmlstream.sent.pop(0)
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
def get_sent_message_xml(self, profile_index):
|
||||
"""Pop and return the sent message in first position (works like a FIFO).
|
||||
Called by tests. FakeClient instances associated to each profile must have
|
||||
been previously initialized with the method FakeSAT.get_client.
|
||||
@return: XML representation of the sent message for given profile, or None"""
|
||||
entry = self.get_sent_message(profile_index)
|
||||
return entry.toXml() if entry else None
|
||||
|
||||
def find_features_set(self, features, identity=None, jid_=None, profile=C.PROF_KEY_NONE):
|
||||
"""Call self.add_feature from your tests to change the return value.
|
||||
|
||||
@return: a set of entities
|
||||
"""
|
||||
client = self.get_client(profile)
|
||||
if jid_ is None:
|
||||
jid_ = JID(client.jid.host)
|
||||
try:
|
||||
if set(features).issubset(client.features[jid_]):
|
||||
return defer.succeed(set([jid_]))
|
||||
except (TypeError, AttributeError, KeyError):
|
||||
pass
|
||||
return defer.succeed(set())
|
||||
|
||||
def add_feature(self, jid_, feature, profile_key):
|
||||
"""Add a feature to an entity.
|
||||
|
||||
To be called from your tests when needed.
|
||||
"""
|
||||
client = self.get_client(profile_key)
|
||||
if not hasattr(client, 'features'):
|
||||
client.features = {}
|
||||
if jid_ not in client.features:
|
||||
client.features[jid_] = set()
|
||||
client.features[jid_].add(feature)
|
||||
|
||||
|
||||
class FakeBridge(object):
|
||||
"""Class to simulate and test bridge calls"""
|
||||
|
||||
def __init__(self):
|
||||
self.expected_calls = {}
|
||||
|
||||
def expect_call(self, name, *check_args, **check_kwargs):
|
||||
if hasattr(self, name): # queue this new call as one already exists
|
||||
self.expected_calls.setdefault(name, [])
|
||||
self.expected_calls[name].append((check_args, check_kwargs))
|
||||
return
|
||||
|
||||
def check_call(*args, **kwargs):
|
||||
if args != check_args or kwargs != check_kwargs:
|
||||
print("\n\n--------------------")
|
||||
print("Args are not equals:")
|
||||
print("args\n----\n%s (sent)\n%s (wanted)" % (args, check_args))
|
||||
print("kwargs\n------\n%s (sent)\n%s (wanted)" % (kwargs, check_kwargs))
|
||||
print("--------------------\n\n")
|
||||
raise DifferentArgsException
|
||||
delattr(self, name)
|
||||
|
||||
if name in self.expected_calls: # register the next call
|
||||
args, kwargs = self.expected_calls[name].pop(0)
|
||||
if len(self.expected_calls[name]) == 0:
|
||||
del self.expected_calls[name]
|
||||
self.expect_call(name, *args, **kwargs)
|
||||
|
||||
setattr(self, name, check_call)
|
||||
|
||||
def add_method(self, name, int_suffix, in_sign, out_sign, method, async_=False, doc=None):
|
||||
pass
|
||||
|
||||
def add_signal(self, name, int_suffix, signature):
|
||||
pass
|
||||
|
||||
def add_test_callback(self, name, method):
|
||||
"""This can be used to register callbacks for bridge methods AND signals.
|
||||
Contrary to expect_call, this will not check if the method or signal is
|
||||
called/sent with the correct arguments, it will instead run the callback
|
||||
of your choice."""
|
||||
setattr(self, name, method)
|
||||
|
||||
|
||||
class FakeParams(Params):
|
||||
"""Class to simulate and test params object. The methods of Params that could
|
||||
not be run (for example those using the storage attribute must be overwritten
|
||||
by a naive simulation of what they should do."""
|
||||
|
||||
def __init__(self, host, storage):
|
||||
Params.__init__(self, host, storage)
|
||||
self.params = {} # naive simulation of values storage
|
||||
|
||||
def param_set(self, name, value, category, security_limit=-1, profile_key='@NONE@'):
|
||||
profile = self.get_profile_name(profile_key)
|
||||
self.params.setdefault(profile, {})
|
||||
self.params[profile_key][(category, name)] = value
|
||||
|
||||
def param_get_a(self, name, category, attr="value", profile_key='@NONE@'):
|
||||
profile = self.get_profile_name(profile_key)
|
||||
return self.params[profile][(category, name)]
|
||||
|
||||
def get_profile_name(self, profile_key, return_profile_keys=False):
|
||||
if profile_key == '@DEFAULT@':
|
||||
return C.PROFILE[0]
|
||||
elif profile_key == '@NONE@':
|
||||
raise exceptions.ProfileNotSetError
|
||||
else:
|
||||
return profile_key
|
||||
|
||||
def load_ind_params(self, profile, cache=None):
|
||||
self.params[profile] = {}
|
||||
return defer.succeed(None)
|
||||
|
||||
|
||||
class FakeMemory(Memory):
|
||||
"""Class to simulate and test memory object"""
|
||||
|
||||
def __init__(self, host):
|
||||
# do not call Memory.__init__, we just want to call the methods that are
|
||||
# manipulating basic stuff, the others should be overwritten when needed
|
||||
self.host = host
|
||||
self.params = FakeParams(host, None)
|
||||
self.config = tools_config.parse_main_conf()
|
||||
self.reinit()
|
||||
|
||||
def reinit(self):
|
||||
"""Tests that manipulate params, entities, features should
|
||||
re-initialise the memory first to not fake the result."""
|
||||
self.params.load_default_params()
|
||||
self.params.params.clear()
|
||||
self.params.frontends_cache = []
|
||||
self.entities_data = {}
|
||||
|
||||
def get_profile_name(self, profile_key, return_profile_keys=False):
|
||||
return self.params.get_profile_name(profile_key, return_profile_keys)
|
||||
|
||||
def add_to_history(self, from_jid, to_jid, message, _type='chat', extra=None, timestamp=None, profile="@NONE@"):
|
||||
pass
|
||||
|
||||
def contact_add(self, contact_jid, attributes, groups, profile_key='@DEFAULT@'):
|
||||
pass
|
||||
|
||||
def set_presence_status(self, contact_jid, show, priority, statuses, profile_key='@DEFAULT@'):
|
||||
pass
|
||||
|
||||
def add_waiting_sub(self, type_, contact_jid, profile_key):
|
||||
pass
|
||||
|
||||
def del_waiting_sub(self, contact_jid, profile_key):
|
||||
pass
|
||||
|
||||
def update_entity_data(self, entity_jid, key, value, silent=False, profile_key="@NONE@"):
|
||||
self.entities_data.setdefault(entity_jid, {})
|
||||
self.entities_data[entity_jid][key] = value
|
||||
|
||||
def entity_data_get(self, entity_jid, keys, profile_key):
|
||||
result = {}
|
||||
for key in keys:
|
||||
result[key] = self.entities_data[entity_jid][key]
|
||||
return result
|
||||
|
||||
|
||||
class FakeTriggerManager(object):
|
||||
|
||||
def add(self, point_name, callback, priority=0):
|
||||
pass
|
||||
|
||||
def point(self, point_name, *args, **kwargs):
|
||||
"""We always return true to continue the action"""
|
||||
return True
|
||||
|
||||
|
||||
class FakeRosterProtocol(SatRosterProtocol):
|
||||
"""This class is used by FakeClient (one instance per profile)"""
|
||||
|
||||
def __init__(self, host, parent):
|
||||
SatRosterProtocol.__init__(self, host)
|
||||
self.parent = parent
|
||||
self._jids = {}
|
||||
self.add_item(parent.jid.userhostJID())
|
||||
|
||||
def add_item(self, jid, *args, **kwargs):
|
||||
if not args and not kwargs:
|
||||
# defaults values setted for the tests only
|
||||
kwargs["subscriptionTo"] = True
|
||||
kwargs["subscriptionFrom"] = True
|
||||
roster_item = RosterItem(jid, *args, **kwargs)
|
||||
attrs = {'to': b2s(roster_item.subscriptionTo), 'from': b2s(roster_item.subscriptionFrom), 'ask': b2s(roster_item.pendingOut)}
|
||||
if roster_item.name:
|
||||
attrs['name'] = roster_item.name
|
||||
self.host.bridge.expect_call("contact_new", jid.full(), attrs, roster_item.groups, self.parent.profile)
|
||||
self._jids[jid] = roster_item
|
||||
self._register_item(roster_item)
|
||||
|
||||
|
||||
class FakeXmlStream(object):
|
||||
"""This class is used by FakeClient (one instance per profile)"""
|
||||
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def send(self, obj):
|
||||
"""Save the sent messages to compare them later.
|
||||
|
||||
@param obj (domish.Element, str or unicode): message to send
|
||||
"""
|
||||
if not isinstance(obj, domish.Element):
|
||||
assert(isinstance(obj, str) or isinstance(obj, str))
|
||||
obj = parseXml(obj)
|
||||
|
||||
if obj.name == 'iq':
|
||||
# IQ request expects an answer, return the request itself so
|
||||
# you can check if it has been well built by your plugin.
|
||||
self.iqDeferreds[obj['id']].callback(obj)
|
||||
|
||||
self.sent.append(obj)
|
||||
return defer.succeed(None)
|
||||
|
||||
def addObserver(self, *argv):
|
||||
pass
|
||||
|
||||
|
||||
class FakeClient(object):
|
||||
"""Tests involving more than one profile need one instance of this class per profile"""
|
||||
|
||||
def __init__(self, host, profile=None):
|
||||
self.host = host
|
||||
self.profile = profile if profile else C.PROFILE[0]
|
||||
self.jid = C.PROFILE_DICT[self.profile]
|
||||
self.roster = FakeRosterProtocol(host, self)
|
||||
self.xmlstream = FakeXmlStream()
|
||||
|
||||
def reinit(self):
|
||||
self.xmlstream = FakeXmlStream()
|
||||
|
||||
def send(self, obj):
|
||||
return self.xmlstream.send(obj)
|
||||
|
||||
|
||||
class SatTestCase(unittest.TestCase):
|
||||
|
||||
def assert_equal_xml(self, xml, expected, ignore_blank=False):
|
||||
def equal_elt(got_elt, exp_elt):
|
||||
if ignore_blank:
|
||||
for elt in got_elt, exp_elt:
|
||||
for attr in ('text', 'tail'):
|
||||
value = getattr(elt, attr)
|
||||
try:
|
||||
value = value.strip() or None
|
||||
except AttributeError:
|
||||
value = None
|
||||
setattr(elt, attr, value)
|
||||
if (got_elt.tag != exp_elt.tag):
|
||||
print("XML are not equals (elt %s/%s):" % (got_elt, exp_elt))
|
||||
print("tag: got [%s] expected: [%s]" % (got_elt.tag, exp_elt.tag))
|
||||
return False
|
||||
if (got_elt.attrib != exp_elt.attrib):
|
||||
print("XML are not equals (elt %s/%s):" % (got_elt, exp_elt))
|
||||
print("attribs: got %s expected %s" % (got_elt.attrib, exp_elt.attrib))
|
||||
return False
|
||||
if (got_elt.tail != exp_elt.tail or got_elt.text != exp_elt.text):
|
||||
print("XML are not equals (elt %s/%s):" % (got_elt, exp_elt))
|
||||
print("text: got [%s] expected: [%s]" % (got_elt.text, exp_elt.text))
|
||||
print("tail: got [%s] expected: [%s]" % (got_elt.tail, exp_elt.tail))
|
||||
return False
|
||||
if (len(got_elt) != len(exp_elt)):
|
||||
print("XML are not equals (elt %s/%s):" % (got_elt, exp_elt))
|
||||
print("children len: got %d expected: %d" % (len(got_elt), len(exp_elt)))
|
||||
return False
|
||||
for idx, child in enumerate(got_elt):
|
||||
if not equal_elt(child, exp_elt[idx]):
|
||||
return False
|
||||
return True
|
||||
|
||||
def remove_blank(xml):
|
||||
lines = [line.strip() for line in re.sub(r'[ \t\r\f\v]+', ' ', xml).split('\n')]
|
||||
return '\n'.join([line for line in lines if line])
|
||||
|
||||
xml_elt = etree.fromstring(remove_blank(xml) if ignore_blank else xml)
|
||||
expected_elt = etree.fromstring(remove_blank(expected) if ignore_blank else expected)
|
||||
|
||||
if not equal_elt(xml_elt, expected_elt):
|
||||
print("---")
|
||||
print("XML are not equals:")
|
||||
print("got:\n-\n%s\n-\n\n" % etree.tostring(xml_elt, encoding='utf-8'))
|
||||
print("was expecting:\n-\n%s\n-\n\n" % etree.tostring(expected_elt, encoding='utf-8'))
|
||||
print("---")
|
||||
raise DifferentXMLException
|
||||
|
||||
def assert_equal_unsorted_list(self, a, b, msg):
|
||||
counter_a = Counter(a)
|
||||
counter_b = Counter(b)
|
||||
if counter_a != counter_b:
|
||||
print("---")
|
||||
print("Unsorted lists are not equals:")
|
||||
print("got : %s" % counter_a)
|
||||
print("was expecting: %s" % counter_b)
|
||||
if msg:
|
||||
print(msg)
|
||||
print("---")
|
||||
raise DifferentListException
|
||||
301
libervia/backend/test/helpers_plugins.py
Normal file
301
libervia/backend/test/helpers_plugins.py
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Helpers class for plugin dependencies """
|
||||
|
||||
from twisted.internet import defer
|
||||
|
||||
from wokkel.muc import Room, User
|
||||
from wokkel.generic import parseXml
|
||||
from wokkel.disco import DiscoItem, DiscoItems
|
||||
|
||||
# temporary until the changes are integrated to Wokkel
|
||||
from sat_tmp.wokkel.rsm import RSMResponse
|
||||
|
||||
from .constants import Const as C
|
||||
from libervia.backend.plugins import plugin_xep_0045
|
||||
from collections import OrderedDict
|
||||
|
||||
|
||||
class FakeMUCClient(object):
|
||||
def __init__(self, plugin_parent):
|
||||
self.plugin_parent = plugin_parent
|
||||
self.host = plugin_parent.host
|
||||
self.joined_rooms = {}
|
||||
|
||||
def join(self, room_jid, nick, options=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""
|
||||
@param room_jid: the room JID
|
||||
@param nick: nick to be used in the room
|
||||
@param options: joining options
|
||||
@param profile_key: the profile key of the user joining the room
|
||||
@return: the deferred joined wokkel.muc.Room instance
|
||||
"""
|
||||
profile = self.host.memory.get_profile_name(profile_key)
|
||||
roster = {}
|
||||
|
||||
# ask the other profiles to fill our roster
|
||||
for i in range(0, len(C.PROFILE)):
|
||||
other_profile = C.PROFILE[i]
|
||||
if other_profile == profile:
|
||||
continue
|
||||
try:
|
||||
other_room = self.plugin_parent.clients[other_profile].joined_rooms[
|
||||
room_jid
|
||||
]
|
||||
roster.setdefault(
|
||||
other_room.nick, User(other_room.nick, C.PROFILE_DICT[other_profile])
|
||||
)
|
||||
for other_nick in other_room.roster:
|
||||
roster.setdefault(other_nick, other_room.roster[other_nick])
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
||||
|
||||
# rename our nick if it already exists
|
||||
while nick in list(roster.keys()):
|
||||
if C.PROFILE_DICT[profile].userhost() == roster[nick].entity.userhost():
|
||||
break # same user with different resource --> same nickname
|
||||
nick = nick + "_"
|
||||
|
||||
room = Room(room_jid, nick)
|
||||
room.roster = roster
|
||||
self.joined_rooms[room_jid] = room
|
||||
|
||||
# fill the other rosters with the new entry
|
||||
for i in range(0, len(C.PROFILE)):
|
||||
other_profile = C.PROFILE[i]
|
||||
if other_profile == profile:
|
||||
continue
|
||||
try:
|
||||
other_room = self.plugin_parent.clients[other_profile].joined_rooms[
|
||||
room_jid
|
||||
]
|
||||
other_room.roster.setdefault(
|
||||
room.nick, User(room.nick, C.PROFILE_DICT[profile])
|
||||
)
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
||||
|
||||
return defer.succeed(room)
|
||||
|
||||
def leave(self, roomJID, profile_key=C.PROF_KEY_NONE):
|
||||
"""
|
||||
@param roomJID: the room JID
|
||||
@param profile_key: the profile key of the user joining the room
|
||||
@return: a dummy deferred
|
||||
"""
|
||||
profile = self.host.memory.get_profile_name(profile_key)
|
||||
room = self.joined_rooms[roomJID]
|
||||
# remove ourself from the other rosters
|
||||
for i in range(0, len(C.PROFILE)):
|
||||
other_profile = C.PROFILE[i]
|
||||
if other_profile == profile:
|
||||
continue
|
||||
try:
|
||||
other_room = self.plugin_parent.clients[other_profile].joined_rooms[
|
||||
roomJID
|
||||
]
|
||||
del other_room.roster[room.nick]
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
||||
del self.joined_rooms[roomJID]
|
||||
return defer.Deferred()
|
||||
|
||||
|
||||
class FakeXEP_0045(plugin_xep_0045.XEP_0045):
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
self.clients = {}
|
||||
for profile in C.PROFILE:
|
||||
self.clients[profile] = FakeMUCClient(self)
|
||||
|
||||
def join(self, room_jid, nick, options={}, profile_key="@DEFAULT@"):
|
||||
"""
|
||||
@param roomJID: the room JID
|
||||
@param nick: nick to be used in the room
|
||||
@param options: ignore
|
||||
@param profile_key: the profile of the user joining the room
|
||||
@return: the deferred joined wokkel.muc.Room instance or None
|
||||
"""
|
||||
profile = self.host.memory.get_profile_name(profile_key)
|
||||
if room_jid in self.clients[profile].joined_rooms:
|
||||
return defer.succeed(None)
|
||||
room = self.clients[profile].join(room_jid, nick, profile_key=profile)
|
||||
return room
|
||||
|
||||
def join_room(self, muc_index, user_index):
|
||||
"""Called by tests
|
||||
@return: the nickname of the user who joined room"""
|
||||
muc_jid = C.MUC[muc_index]
|
||||
nick = C.JID[user_index].user
|
||||
profile = C.PROFILE[user_index]
|
||||
self.join(muc_jid, nick, profile_key=profile)
|
||||
return self.get_nick(muc_index, user_index)
|
||||
|
||||
def leave(self, room_jid, profile_key="@DEFAULT@"):
|
||||
"""
|
||||
@param roomJID: the room JID
|
||||
@param profile_key: the profile of the user leaving the room
|
||||
@return: a dummy deferred
|
||||
"""
|
||||
profile = self.host.memory.get_profile_name(profile_key)
|
||||
if room_jid not in self.clients[profile].joined_rooms:
|
||||
raise plugin_xep_0045.UnknownRoom("This room has not been joined")
|
||||
return self.clients[profile].leave(room_jid, profile)
|
||||
|
||||
def leave_room(self, muc_index, user_index):
|
||||
"""Called by tests
|
||||
@return: the nickname of the user who left the room"""
|
||||
muc_jid = C.MUC[muc_index]
|
||||
nick = self.get_nick(muc_index, user_index)
|
||||
profile = C.PROFILE[user_index]
|
||||
self.leave(muc_jid, profile_key=profile)
|
||||
return nick
|
||||
|
||||
def get_room(self, muc_index, user_index):
|
||||
"""Called by tests
|
||||
@return: a wokkel.muc.Room instance"""
|
||||
profile = C.PROFILE[user_index]
|
||||
muc_jid = C.MUC[muc_index]
|
||||
try:
|
||||
return self.clients[profile].joined_rooms[muc_jid]
|
||||
except (AttributeError, KeyError):
|
||||
return None
|
||||
|
||||
def get_nick(self, muc_index, user_index):
|
||||
try:
|
||||
return self.get_room_nick(C.MUC[muc_index], C.PROFILE[user_index])
|
||||
except (KeyError, AttributeError):
|
||||
return ""
|
||||
|
||||
def get_nick_of_user(self, muc_index, user_index, profile_index, secure=True):
|
||||
try:
|
||||
room = self.clients[C.PROFILE[profile_index]].joined_rooms[C.MUC[muc_index]]
|
||||
return self.getRoomNickOfUser(room, C.JID[user_index])
|
||||
except (KeyError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
class FakeXEP_0249(object):
|
||||
def __init__(self, host):
|
||||
self.host = host
|
||||
|
||||
def invite(self, target, room, options={}, profile_key="@DEFAULT@"):
|
||||
"""
|
||||
Invite a user to a room. To accept the invitation from a test,
|
||||
just call FakeXEP_0045.join_room (no need to have a dedicated method).
|
||||
@param target: jid of the user to invite
|
||||
@param room: jid of the room where the user is invited
|
||||
@options: attribute with extra info (reason, password) as in #XEP-0249
|
||||
@profile_key: %(doc_profile_key)s
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class FakeSatPubSubClient(object):
|
||||
def __init__(self, host, parent_plugin):
|
||||
self.host = host
|
||||
self.parent_plugin = parent_plugin
|
||||
self.__items = OrderedDict()
|
||||
self.__rsm_responses = {}
|
||||
|
||||
def createNode(self, service, nodeIdentifier=None, options=None, sender=None):
|
||||
return defer.succeed(None)
|
||||
|
||||
def deleteNode(self, service, nodeIdentifier, sender=None):
|
||||
try:
|
||||
del self.__items[nodeIdentifier]
|
||||
except KeyError:
|
||||
pass
|
||||
return defer.succeed(None)
|
||||
|
||||
def subscribe(self, service, nodeIdentifier, subscriber, options=None, sender=None):
|
||||
return defer.succeed(None)
|
||||
|
||||
def unsubscribe(
|
||||
self,
|
||||
service,
|
||||
nodeIdentifier,
|
||||
subscriber,
|
||||
subscriptionIdentifier=None,
|
||||
sender=None,
|
||||
):
|
||||
return defer.succeed(None)
|
||||
|
||||
def publish(self, service, nodeIdentifier, items=None, sender=None):
|
||||
node = self.__items.setdefault(nodeIdentifier, [])
|
||||
|
||||
def replace(item_obj):
|
||||
index = 0
|
||||
for current in node:
|
||||
if current["id"] == item_obj["id"]:
|
||||
node[index] = item_obj
|
||||
return True
|
||||
index += 1
|
||||
return False
|
||||
|
||||
for item in items:
|
||||
item_obj = parseXml(item) if isinstance(item, str) else item
|
||||
if not replace(item_obj):
|
||||
node.append(item_obj)
|
||||
return defer.succeed(None)
|
||||
|
||||
def items(
|
||||
self,
|
||||
service,
|
||||
nodeIdentifier,
|
||||
maxItems=None,
|
||||
itemIdentifiers=None,
|
||||
subscriptionIdentifier=None,
|
||||
sender=None,
|
||||
ext_data=None,
|
||||
):
|
||||
try:
|
||||
items = self.__items[nodeIdentifier]
|
||||
except KeyError:
|
||||
items = []
|
||||
if ext_data:
|
||||
assert "id" in ext_data
|
||||
if "rsm" in ext_data:
|
||||
args = (0, items[0]["id"], items[-1]["id"]) if items else ()
|
||||
self.__rsm_responses[ext_data["id"]] = RSMResponse(len(items), *args)
|
||||
return defer.succeed(items)
|
||||
|
||||
def retract_items(self, service, nodeIdentifier, itemIdentifiers, sender=None):
|
||||
node = self.__items[nodeIdentifier]
|
||||
for item in [item for item in node if item["id"] in itemIdentifiers]:
|
||||
node.remove(item)
|
||||
return defer.succeed(None)
|
||||
|
||||
def get_rsm_response(self, id):
|
||||
if id not in self.__rsm_responses:
|
||||
return {}
|
||||
result = self.__rsm_responses[id].toDict()
|
||||
del self.__rsm_responses[id]
|
||||
return result
|
||||
|
||||
def subscriptions(self, service, nodeIdentifier, sender=None):
|
||||
return defer.succeed([])
|
||||
|
||||
def service_get_disco_items(self, service, nodeIdentifier, profile_key=C.PROF_KEY_NONE):
|
||||
items = DiscoItems()
|
||||
for item in list(self.__items.keys()):
|
||||
items.append(DiscoItem(service, item))
|
||||
return defer.succeed(items)
|
||||
111
libervia/backend/test/test_core_xmpp.py
Normal file
111
libervia/backend/test/test_core_xmpp.py
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from .constants import Const
|
||||
from twisted.trial import unittest
|
||||
from libervia.backend.core import xmpp
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from wokkel.generic import parseXml
|
||||
from wokkel.xmppim import RosterItem
|
||||
|
||||
|
||||
class SatXMPPClientTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.client = xmpp.SatXMPPClient(self.host, Const.PROFILE[0], JID("test@example.org"), "test")
|
||||
|
||||
def test_init(self):
|
||||
"""Check that init values are correctly initialised"""
|
||||
self.assertEqual(self.client.profile, Const.PROFILE[0])
|
||||
print(self.client.jid.host)
|
||||
self.assertEqual(self.client.host_app, self.host)
|
||||
|
||||
|
||||
class SatMessageProtocolTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.message = xmpp.SatMessageProtocol(self.host)
|
||||
self.message.parent = helpers.FakeClient(self.host)
|
||||
|
||||
def test_on_message(self):
|
||||
xml = """
|
||||
<message type="chat" from="sender@example.net/house" to="test@example.org/SàT" id="test_1">
|
||||
<body>test</body>
|
||||
</message>
|
||||
"""
|
||||
stanza = parseXml(xml)
|
||||
self.host.bridge.expect_call("message_new", "sender@example.net/house", "test", "chat", "test@example.org/SàT", {}, profile=Const.PROFILE[0])
|
||||
self.message.onMessage(stanza)
|
||||
|
||||
|
||||
class SatRosterProtocolTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.roster = xmpp.SatRosterProtocol(self.host)
|
||||
self.roster.parent = helpers.FakeClient(self.host)
|
||||
|
||||
def test_register_item(self):
|
||||
roster_item = RosterItem(Const.JID[0])
|
||||
roster_item.name = "Test Man"
|
||||
roster_item.subscriptionTo = True
|
||||
roster_item.subscriptionFrom = True
|
||||
roster_item.ask = False
|
||||
roster_item.groups = set(["Test Group 1", "Test Group 2", "Test Group 3"])
|
||||
self.host.bridge.expect_call("contact_new", Const.JID_STR[0], {'to': 'True', 'from': 'True', 'ask': 'False', 'name': 'Test Man'}, set(["Test Group 1", "Test Group 2", "Test Group 3"]), Const.PROFILE[0])
|
||||
self.roster._register_item(roster_item)
|
||||
|
||||
|
||||
class SatPresenceProtocolTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.presence = xmpp.SatPresenceProtocol(self.host)
|
||||
self.presence.parent = helpers.FakeClient(self.host)
|
||||
|
||||
def test_availableReceived(self):
|
||||
self.host.bridge.expect_call("presence_update", Const.JID_STR[0], "xa", 15, {'default': "test status", 'fr': 'statut de test'}, Const.PROFILE[0])
|
||||
self.presence.availableReceived(Const.JID[0], 'xa', {None: "test status", 'fr': 'statut de test'}, 15)
|
||||
|
||||
def test_available_received_empty_statuses(self):
|
||||
self.host.bridge.expect_call("presence_update", Const.JID_STR[0], "xa", 15, {}, Const.PROFILE[0])
|
||||
self.presence.availableReceived(Const.JID[0], 'xa', None, 15)
|
||||
|
||||
def test_unavailableReceived(self):
|
||||
self.host.bridge.expect_call("presence_update", Const.JID_STR[0], "unavailable", 0, {}, Const.PROFILE[0])
|
||||
self.presence.unavailableReceived(Const.JID[0], None)
|
||||
|
||||
def test_subscribedReceived(self):
|
||||
self.host.bridge.expect_call("subscribe", "subscribed", Const.JID[0].userhost(), Const.PROFILE[0])
|
||||
self.presence.subscribedReceived(Const.JID[0])
|
||||
|
||||
def test_unsubscribedReceived(self):
|
||||
self.host.bridge.expect_call("subscribe", "unsubscribed", Const.JID[0].userhost(), Const.PROFILE[0])
|
||||
self.presence.unsubscribedReceived(Const.JID[0])
|
||||
|
||||
def test_subscribeReceived(self):
|
||||
self.host.bridge.expect_call("subscribe", "subscribe", Const.JID[0].userhost(), Const.PROFILE[0])
|
||||
self.presence.subscribeReceived(Const.JID[0])
|
||||
|
||||
def test_unsubscribeReceived(self):
|
||||
self.host.bridge.expect_call("subscribe", "unsubscribe", Const.JID[0].userhost(), Const.PROFILE[0])
|
||||
self.presence.unsubscribeReceived(Const.JID[0])
|
||||
124
libervia/backend/test/test_helpers_plugins.py
Normal file
124
libervia/backend/test/test_helpers_plugins.py
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Test the helper classes to see if they behave well"""
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.test import helpers_plugins
|
||||
|
||||
|
||||
class FakeXEP_0045Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = helpers_plugins.FakeXEP_0045(self.host)
|
||||
|
||||
def test_join_room(self):
|
||||
self.plugin.join_room(0, 0)
|
||||
self.assertEqual("test", self.plugin.get_nick(0, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 0))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 1))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 2))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 3))
|
||||
self.plugin.join_room(0, 1)
|
||||
self.assertEqual("test", self.plugin.get_nick(0, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick(0, 1))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 1))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 2))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 2))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 3))
|
||||
self.plugin.join_room(0, 2)
|
||||
self.assertEqual("test", self.plugin.get_nick(0, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick(0, 1))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 1))
|
||||
self.assertEqual(
|
||||
"sender", self.plugin.get_nick_of_user(0, 1, 1)
|
||||
) # Const.JID[2] is in the roster for Const.PROFILE[1]
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 1))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 1))
|
||||
self.assertEqual("sender", self.plugin.get_nick(0, 2))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 2))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 2))
|
||||
self.assertEqual(
|
||||
"sender", self.plugin.get_nick_of_user(0, 2, 2)
|
||||
) # Const.JID[1] is in the roster for Const.PROFILE[2]
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 2))
|
||||
self.assertEqual("", self.plugin.get_nick(0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 1, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 2, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 3))
|
||||
self.plugin.join_room(0, 3)
|
||||
self.assertEqual("test", self.plugin.get_nick(0, 0))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 0, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 0))
|
||||
self.assertEqual("sender_", self.plugin.get_nick_of_user(0, 3, 0))
|
||||
self.assertEqual("sender", self.plugin.get_nick(0, 1))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 1))
|
||||
self.assertEqual(
|
||||
"sender", self.plugin.get_nick_of_user(0, 1, 1)
|
||||
) # Const.JID[2] is in the roster for Const.PROFILE[1]
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 1))
|
||||
self.assertEqual("sender_", self.plugin.get_nick_of_user(0, 3, 1))
|
||||
self.assertEqual("sender", self.plugin.get_nick(0, 2))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 2))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 2))
|
||||
self.assertEqual(
|
||||
"sender", self.plugin.get_nick_of_user(0, 2, 2)
|
||||
) # Const.JID[1] is in the roster for Const.PROFILE[2]
|
||||
self.assertEqual("sender_", self.plugin.get_nick_of_user(0, 3, 2))
|
||||
self.assertEqual("sender_", self.plugin.get_nick(0, 3))
|
||||
self.assertEqual("test", self.plugin.get_nick_of_user(0, 0, 3))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 1, 3))
|
||||
self.assertEqual("sender", self.plugin.get_nick_of_user(0, 2, 3))
|
||||
self.assertEqual(None, self.plugin.get_nick_of_user(0, 3, 3))
|
||||
313
libervia/backend/test/test_memory.py
Normal file
313
libervia/backend/test/test_memory.py
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from libervia.backend.core.i18n import _
|
||||
from libervia.backend.test import helpers
|
||||
from twisted.trial import unittest
|
||||
import traceback
|
||||
from .constants import Const
|
||||
from xml.dom import minidom
|
||||
|
||||
|
||||
class MemoryTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
|
||||
def _get_param_xml(self, param="1", security_level=None):
|
||||
"""Generate XML for testing parameters
|
||||
|
||||
@param param (str): a subset of "123"
|
||||
@param security_level: security level of the parameters
|
||||
@return (str)
|
||||
"""
|
||||
|
||||
def get_param(name):
|
||||
return """
|
||||
<param name="%(param_name)s" label="%(param_label)s" value="true" type="bool" %(security)s/>
|
||||
""" % {
|
||||
"param_name": name,
|
||||
"param_label": _(name),
|
||||
"security": ""
|
||||
if security_level is None
|
||||
else ('security="%d"' % security_level),
|
||||
}
|
||||
|
||||
params = ""
|
||||
if "1" in param:
|
||||
params += get_param(Const.ENABLE_UNIBOX_PARAM)
|
||||
if "2" in param:
|
||||
params += get_param(Const.PARAM_IN_QUOTES)
|
||||
if "3" in param:
|
||||
params += get_param("Dummy param")
|
||||
return """
|
||||
<params>
|
||||
<individual>
|
||||
<category name="%(category_name)s" label="%(category_label)s">
|
||||
%(params)s
|
||||
</category>
|
||||
</individual>
|
||||
</params>
|
||||
""" % {
|
||||
"category_name": Const.COMPOSITION_KEY,
|
||||
"category_label": _(Const.COMPOSITION_KEY),
|
||||
"params": params,
|
||||
}
|
||||
|
||||
def _param_exists(self, param="1", src=None):
|
||||
"""
|
||||
|
||||
@param param (str): a character in "12"
|
||||
@param src (DOM element): the top-level element to look in
|
||||
@return: True is the param exists
|
||||
"""
|
||||
if param == "1":
|
||||
name = Const.ENABLE_UNIBOX_PARAM
|
||||
else:
|
||||
name = Const.PARAM_IN_QUOTES
|
||||
category = Const.COMPOSITION_KEY
|
||||
if src is None:
|
||||
src = self.host.memory.params.dom.documentElement
|
||||
for type_node in src.childNodes:
|
||||
# when src comes self.host.memory.params.dom, we have here
|
||||
# some "individual" or "general" elements, when it comes
|
||||
# from Memory.get_params we have here a "params" elements
|
||||
if type_node.nodeName not in ("individual", "general", "params"):
|
||||
continue
|
||||
for cat_node in type_node.childNodes:
|
||||
if (
|
||||
cat_node.nodeName != "category"
|
||||
or cat_node.getAttribute("name") != category
|
||||
):
|
||||
continue
|
||||
for param in cat_node.childNodes:
|
||||
if param.nodeName == "param" and param.getAttribute("name") == name:
|
||||
return True
|
||||
return False
|
||||
|
||||
def assert_param_generic(self, param="1", src=None, exists=True, deferred=False):
|
||||
"""
|
||||
@param param (str): a character in "12"
|
||||
@param src (DOM element): the top-level element to look in
|
||||
@param exists (boolean): True to assert the param exists, False to assert it doesn't
|
||||
@param deferred (boolean): True if this method is called from a Deferred callback
|
||||
"""
|
||||
msg = (
|
||||
"Expected parameter not found!\n"
|
||||
if exists
|
||||
else "Unexpected parameter found!\n"
|
||||
)
|
||||
if deferred:
|
||||
# in this stack we can see the line where the error came from,
|
||||
# if limit=5, 6 is not enough you can increase the value
|
||||
msg += "\n".join(traceback.format_stack(limit=5 if exists else 6))
|
||||
assertion = self._param_exists(param, src)
|
||||
getattr(self, "assert%s" % exists)(assertion, msg)
|
||||
|
||||
def assert_param_exists(self, param="1", src=None):
|
||||
self.assert_param_generic(param, src, True)
|
||||
|
||||
def assert_param_not_exists(self, param="1", src=None):
|
||||
self.assert_param_generic(param, src, False)
|
||||
|
||||
def assert_param_exists_async(self, src, param="1"):
|
||||
"""@param src: a deferred result from Memory.get_params"""
|
||||
self.assert_param_generic(
|
||||
param, minidom.parseString(src.encode("utf-8")), True, True
|
||||
)
|
||||
|
||||
def assert_param_not_exists_async(self, src, param="1"):
|
||||
"""@param src: a deferred result from Memory.get_params"""
|
||||
self.assert_param_generic(
|
||||
param, minidom.parseString(src.encode("utf-8")), False, True
|
||||
)
|
||||
|
||||
def _get_params(self, security_limit, app="", profile_key="@NONE@"):
|
||||
"""Get the parameters accessible with the given security limit and application name.
|
||||
|
||||
@param security_limit (int): the security limit
|
||||
@param app (str): empty string or "libervia"
|
||||
@param profile_key
|
||||
"""
|
||||
if profile_key == "@NONE@":
|
||||
profile_key = "@DEFAULT@"
|
||||
return self.host.memory.params.get_params(security_limit, app, profile_key)
|
||||
|
||||
def test_update_params(self):
|
||||
self.host.memory.reinit()
|
||||
# check if the update works
|
||||
self.host.memory.update_params(self._get_param_xml())
|
||||
self.assert_param_exists()
|
||||
previous = self.host.memory.params.dom.cloneNode(True)
|
||||
# now check if it is really updated and not duplicated
|
||||
self.host.memory.update_params(self._get_param_xml())
|
||||
self.assertEqual(
|
||||
previous.toxml().encode("utf-8"),
|
||||
self.host.memory.params.dom.toxml().encode("utf-8"),
|
||||
)
|
||||
|
||||
self.host.memory.reinit()
|
||||
# check successive updates (without intersection)
|
||||
self.host.memory.update_params(self._get_param_xml("1"))
|
||||
self.assert_param_exists("1")
|
||||
self.assert_param_not_exists("2")
|
||||
self.host.memory.update_params(self._get_param_xml("2"))
|
||||
self.assert_param_exists("1")
|
||||
self.assert_param_exists("2")
|
||||
|
||||
previous = self.host.memory.params.dom.cloneNode(True) # save for later
|
||||
|
||||
self.host.memory.reinit()
|
||||
# check successive updates (with intersection)
|
||||
self.host.memory.update_params(self._get_param_xml("1"))
|
||||
self.assert_param_exists("1")
|
||||
self.assert_param_not_exists("2")
|
||||
self.host.memory.update_params(self._get_param_xml("12"))
|
||||
self.assert_param_exists("1")
|
||||
self.assert_param_exists("2")
|
||||
|
||||
# successive updates with or without intersection should have the same result
|
||||
self.assertEqual(
|
||||
previous.toxml().encode("utf-8"),
|
||||
self.host.memory.params.dom.toxml().encode("utf-8"),
|
||||
)
|
||||
|
||||
self.host.memory.reinit()
|
||||
# one update with two params in a new category
|
||||
self.host.memory.update_params(self._get_param_xml("12"))
|
||||
self.assert_param_exists("1")
|
||||
self.assert_param_exists("2")
|
||||
|
||||
def test_get_params(self):
|
||||
# tests with no security level on the parameter (most secure)
|
||||
params = self._get_param_xml()
|
||||
self.host.memory.reinit()
|
||||
self.host.memory.update_params(params)
|
||||
self._get_params(Const.NO_SECURITY_LIMIT).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(0).addCallback(self.assert_param_not_exists_async)
|
||||
self._get_params(1).addCallback(self.assert_param_not_exists_async)
|
||||
# tests with security level 0 on the parameter (not secure)
|
||||
params = self._get_param_xml(security_level=0)
|
||||
self.host.memory.reinit()
|
||||
self.host.memory.update_params(params)
|
||||
self._get_params(Const.NO_SECURITY_LIMIT).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(0).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(1).addCallback(self.assert_param_exists_async)
|
||||
# tests with security level 1 on the parameter (more secure)
|
||||
params = self._get_param_xml(security_level=1)
|
||||
self.host.memory.reinit()
|
||||
self.host.memory.update_params(params)
|
||||
self._get_params(Const.NO_SECURITY_LIMIT).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(0).addCallback(self.assert_param_not_exists_async)
|
||||
return self._get_params(1).addCallback(self.assert_param_exists_async)
|
||||
|
||||
def test_params_register_app(self):
|
||||
def register(xml, security_limit, app):
|
||||
"""
|
||||
@param xml: XML definition of the parameters to be added
|
||||
@param security_limit: -1 means no security, 0 is the maximum security then the higher the less secure
|
||||
@param app: name of the frontend registering the parameters
|
||||
"""
|
||||
helpers.mute_logging()
|
||||
self.host.memory.params_register_app(xml, security_limit, app)
|
||||
helpers.unmute_logging()
|
||||
|
||||
# tests with no security level on the parameter (most secure)
|
||||
params = self._get_param_xml()
|
||||
self.host.memory.reinit()
|
||||
register(params, Const.NO_SECURITY_LIMIT, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 0, Const.APP_NAME)
|
||||
self.assert_param_not_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 1, Const.APP_NAME)
|
||||
self.assert_param_not_exists()
|
||||
|
||||
# tests with security level 0 on the parameter (not secure)
|
||||
params = self._get_param_xml(security_level=0)
|
||||
self.host.memory.reinit()
|
||||
register(params, Const.NO_SECURITY_LIMIT, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 0, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 1, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
|
||||
# tests with security level 1 on the parameter (more secure)
|
||||
params = self._get_param_xml(security_level=1)
|
||||
self.host.memory.reinit()
|
||||
register(params, Const.NO_SECURITY_LIMIT, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 0, Const.APP_NAME)
|
||||
self.assert_param_not_exists()
|
||||
self.host.memory.reinit()
|
||||
register(params, 1, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
|
||||
# tests with security level 1 and several parameters being registered
|
||||
params = self._get_param_xml("12", security_level=1)
|
||||
self.host.memory.reinit()
|
||||
register(params, Const.NO_SECURITY_LIMIT, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.assert_param_exists("2")
|
||||
self.host.memory.reinit()
|
||||
register(params, 0, Const.APP_NAME)
|
||||
self.assert_param_not_exists()
|
||||
self.assert_param_not_exists("2")
|
||||
self.host.memory.reinit()
|
||||
register(params, 1, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.assert_param_exists("2")
|
||||
|
||||
# tests with several parameters being registered in an existing category
|
||||
self.host.memory.reinit()
|
||||
self.host.memory.update_params(self._get_param_xml("3"))
|
||||
register(self._get_param_xml("12"), Const.NO_SECURITY_LIMIT, Const.APP_NAME)
|
||||
self.assert_param_exists()
|
||||
self.assert_param_exists("2")
|
||||
self.host.memory.reinit()
|
||||
|
||||
def test_params_register_app_get_params(self):
|
||||
# test retrieving the parameter for a specific frontend
|
||||
self.host.memory.reinit()
|
||||
params = self._get_param_xml(security_level=1)
|
||||
self.host.memory.params_register_app(params, 1, Const.APP_NAME)
|
||||
self._get_params(1, "").addCallback(self.assert_param_exists_async)
|
||||
self._get_params(1, Const.APP_NAME).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(1, "another_dummy_frontend").addCallback(
|
||||
self.assert_param_not_exists_async
|
||||
)
|
||||
|
||||
# the same with several parameters registered at the same time
|
||||
self.host.memory.reinit()
|
||||
params = self._get_param_xml("12", security_level=0)
|
||||
self.host.memory.params_register_app(params, 5, Const.APP_NAME)
|
||||
self._get_params(5, "").addCallback(self.assert_param_exists_async)
|
||||
self._get_params(5, "").addCallback(self.assert_param_exists_async, "2")
|
||||
self._get_params(5, Const.APP_NAME).addCallback(self.assert_param_exists_async)
|
||||
self._get_params(5, Const.APP_NAME).addCallback(self.assert_param_exists_async, "2")
|
||||
self._get_params(5, "another_dummy_frontend").addCallback(
|
||||
self.assert_param_not_exists_async
|
||||
)
|
||||
return self._get_params(5, "another_dummy_frontend").addCallback(
|
||||
self.assert_param_not_exists_async, "2"
|
||||
)
|
||||
71
libervia/backend/test/test_memory_crypto.py
Normal file
71
libervia/backend/test/test_memory_crypto.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
""" Tests for the plugin radiocol """
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.memory.crypto import BlockCipher, PasswordHasher
|
||||
import random
|
||||
import string
|
||||
from twisted.internet import defer
|
||||
|
||||
|
||||
def get_random_unicode(len):
|
||||
"""Return a random unicode string"""
|
||||
return "".join(random.choice(string.letters + "éáúóâêûôßüöä") for i in range(len))
|
||||
|
||||
|
||||
class CryptoTest(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
|
||||
def test_encrypt_decrypt(self):
|
||||
d_list = []
|
||||
|
||||
def test(key, message):
|
||||
d = BlockCipher.encrypt(key, message)
|
||||
d.addCallback(lambda ciphertext: BlockCipher.decrypt(key, ciphertext))
|
||||
d.addCallback(lambda decrypted: self.assertEqual(message, decrypted))
|
||||
d_list.append(d)
|
||||
|
||||
for key_len in (0, 2, 8, 10, 16, 24, 30, 32, 40):
|
||||
key = get_random_unicode(key_len)
|
||||
for message_len in (0, 2, 16, 24, 32, 100):
|
||||
message = get_random_unicode(message_len)
|
||||
test(key, message)
|
||||
return defer.DeferredList(d_list)
|
||||
|
||||
def test_hash_verify(self):
|
||||
d_list = []
|
||||
for password in (0, 2, 8, 10, 16, 24, 30, 32, 40):
|
||||
d = PasswordHasher.hash(password)
|
||||
|
||||
def cb(hashed):
|
||||
d1 = PasswordHasher.verify(password, hashed)
|
||||
d1.addCallback(lambda result: self.assertTrue(result))
|
||||
d_list.append(d1)
|
||||
attempt = get_random_unicode(10)
|
||||
d2 = PasswordHasher.verify(attempt, hashed)
|
||||
d2.addCallback(lambda result: self.assertFalse(result))
|
||||
d_list.append(d2)
|
||||
|
||||
d.addCallback(cb)
|
||||
return defer.DeferredList(d_list)
|
||||
615
libervia/backend/test/test_plugin_misc_groupblog.py
Normal file
615
libervia/backend/test/test_plugin_misc_groupblog.py
Normal file
|
|
@ -0,0 +1,615 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin groupblogs """
|
||||
|
||||
from .constants import Const as C
|
||||
from libervia.backend.test import helpers, helpers_plugins
|
||||
from libervia.backend.plugins import plugin_misc_groupblog
|
||||
from libervia.backend.plugins import plugin_xep_0060
|
||||
from libervia.backend.plugins import plugin_xep_0277
|
||||
from libervia.backend.plugins import plugin_xep_0163
|
||||
from libervia.backend.plugins import plugin_misc_text_syntaxes
|
||||
from twisted.internet import defer
|
||||
from twisted.words.protocols.jabber import jid
|
||||
import importlib
|
||||
|
||||
|
||||
NS_PUBSUB = "http://jabber.org/protocol/pubsub"
|
||||
|
||||
DO_NOT_COUNT_COMMENTS = -1
|
||||
|
||||
SERVICE = "pubsub.example.com"
|
||||
PUBLISHER = "test@example.org"
|
||||
OTHER_PUBLISHER = "other@xmpp.net"
|
||||
NODE_ID = "urn:xmpp:groupblog:{publisher}".format(publisher=PUBLISHER)
|
||||
OTHER_NODE_ID = "urn:xmpp:groupblog:{publisher}".format(publisher=OTHER_PUBLISHER)
|
||||
ITEM_ID_1 = "c745a688-9b02-11e3-a1a3-c0143dd4fe51"
|
||||
COMMENT_ID_1 = "d745a688-9b02-11e3-a1a3-c0143dd4fe52"
|
||||
COMMENT_ID_2 = "e745a688-9b02-11e3-a1a3-c0143dd4fe53"
|
||||
|
||||
|
||||
def COMMENTS_NODE_ID(publisher=PUBLISHER):
|
||||
return "urn:xmpp:comments:_{id}__urn:xmpp:groupblog:{publisher}".format(
|
||||
id=ITEM_ID_1, publisher=publisher
|
||||
)
|
||||
|
||||
|
||||
def COMMENTS_NODE_URL(publisher=PUBLISHER):
|
||||
return "xmpp:{service}?node={node}".format(
|
||||
service=SERVICE,
|
||||
id=ITEM_ID_1,
|
||||
node=COMMENTS_NODE_ID(publisher).replace(":", "%3A").replace("@", "%40"),
|
||||
)
|
||||
|
||||
|
||||
def ITEM(publisher=PUBLISHER):
|
||||
return """
|
||||
<item id='{id}' xmlns='{ns}'>
|
||||
<entry>
|
||||
<title type='text'>The Uses of This World</title>
|
||||
<id>{id}</id>
|
||||
<updated>2003-12-12T17:47:23Z</updated>
|
||||
<published>2003-12-12T17:47:23Z</published>
|
||||
<link href='{comments_node_url}' rel='replies' title='comments'/>
|
||||
<author>
|
||||
<name>{publisher}</name>
|
||||
</author>
|
||||
</entry>
|
||||
</item>
|
||||
""".format(
|
||||
ns=NS_PUBSUB,
|
||||
id=ITEM_ID_1,
|
||||
publisher=publisher,
|
||||
comments_node_url=COMMENTS_NODE_URL(publisher),
|
||||
)
|
||||
|
||||
|
||||
def COMMENT(id_=COMMENT_ID_1):
|
||||
return """
|
||||
<item id='{id}' xmlns='{ns}'>
|
||||
<entry>
|
||||
<title type='text'>The Uses of This World</title>
|
||||
<id>{id}</id>
|
||||
<updated>2003-12-12T17:47:23Z</updated>
|
||||
<published>2003-12-12T17:47:23Z</published>
|
||||
<author>
|
||||
<name>{publisher}</name>
|
||||
</author>
|
||||
</entry>
|
||||
</item>
|
||||
""".format(
|
||||
ns=NS_PUBSUB, id=id_, publisher=PUBLISHER
|
||||
)
|
||||
|
||||
|
||||
def ITEM_DATA(id_=ITEM_ID_1, count=0):
|
||||
res = {
|
||||
"id": ITEM_ID_1,
|
||||
"type": "main_item",
|
||||
"content": "The Uses of This World",
|
||||
"author": PUBLISHER,
|
||||
"updated": "1071251243.0",
|
||||
"published": "1071251243.0",
|
||||
"service": SERVICE,
|
||||
"comments": COMMENTS_NODE_URL_1,
|
||||
"comments_service": SERVICE,
|
||||
"comments_node": COMMENTS_NODE_ID_1,
|
||||
}
|
||||
if count != DO_NOT_COUNT_COMMENTS:
|
||||
res.update({"comments_count": str(count)})
|
||||
return res
|
||||
|
||||
|
||||
def COMMENT_DATA(id_=COMMENT_ID_1):
|
||||
return {
|
||||
"id": id_,
|
||||
"type": "comment",
|
||||
"content": "The Uses of This World",
|
||||
"author": PUBLISHER,
|
||||
"updated": "1071251243.0",
|
||||
"published": "1071251243.0",
|
||||
"service": SERVICE,
|
||||
"node": COMMENTS_NODE_ID_1,
|
||||
"verified_publisher": "false",
|
||||
}
|
||||
|
||||
|
||||
COMMENTS_NODE_ID_1 = COMMENTS_NODE_ID()
|
||||
COMMENTS_NODE_ID_2 = COMMENTS_NODE_ID(OTHER_PUBLISHER)
|
||||
COMMENTS_NODE_URL_1 = COMMENTS_NODE_URL()
|
||||
COMMENTS_NODE_URL_2 = COMMENTS_NODE_URL(OTHER_PUBLISHER)
|
||||
ITEM_1 = ITEM()
|
||||
ITEM_2 = ITEM(OTHER_PUBLISHER)
|
||||
COMMENT_1 = COMMENT(COMMENT_ID_1)
|
||||
COMMENT_2 = COMMENT(COMMENT_ID_2)
|
||||
|
||||
|
||||
def ITEM_DATA_1(count=0):
|
||||
return ITEM_DATA(count=count)
|
||||
|
||||
|
||||
COMMENT_DATA_1 = COMMENT_DATA()
|
||||
COMMENT_DATA_2 = COMMENT_DATA(COMMENT_ID_2)
|
||||
|
||||
|
||||
class XEP_groupblogTest(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.host.plugins["XEP-0060"] = plugin_xep_0060.XEP_0060(self.host)
|
||||
self.host.plugins["XEP-0163"] = plugin_xep_0163.XEP_0163(self.host)
|
||||
importlib.reload(plugin_misc_text_syntaxes) # reload the plugin to avoid conflict error
|
||||
self.host.plugins["TEXT_SYNTAXES"] = plugin_misc_text_syntaxes.TextSyntaxes(
|
||||
self.host
|
||||
)
|
||||
self.host.plugins["XEP-0277"] = plugin_xep_0277.XEP_0277(self.host)
|
||||
self.plugin = plugin_misc_groupblog.GroupBlog(self.host)
|
||||
self.plugin._initialise = self._initialise
|
||||
self.__initialised = False
|
||||
self._initialise(C.PROFILE[0])
|
||||
|
||||
def _initialise(self, profile_key):
|
||||
profile = profile_key
|
||||
client = self.host.get_client(profile)
|
||||
if not self.__initialised:
|
||||
client.item_access_pubsub = jid.JID(SERVICE)
|
||||
xep_0060 = self.host.plugins["XEP-0060"]
|
||||
client.pubsub_client = helpers_plugins.FakeSatPubSubClient(
|
||||
self.host, xep_0060
|
||||
)
|
||||
client.pubsub_client.parent = client
|
||||
self.psclient = client.pubsub_client
|
||||
helpers.FakeSAT.getDiscoItems = self.psclient.service_get_disco_items
|
||||
self.__initialised = True
|
||||
return defer.succeed((profile, client))
|
||||
|
||||
def _add_item(self, profile, item, parent_node=None):
|
||||
client = self.host.get_client(profile)
|
||||
client.pubsub_client._add_item(item, parent_node)
|
||||
|
||||
def test_send_group_blog(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.items(SERVICE, NODE_ID)
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.sendGroupBlog(
|
||||
"PUBLIC", [], "test", {}, C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
return d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
|
||||
def test_delete_group_blog(self):
|
||||
pub_data = (SERVICE, NODE_ID, ITEM_ID_1)
|
||||
self.host.bridge.expect_call(
|
||||
"personalEvent",
|
||||
C.JID_STR[0],
|
||||
"MICROBLOG_DELETE",
|
||||
{"type": "main_item", "id": ITEM_ID_1},
|
||||
C.PROFILE[0],
|
||||
)
|
||||
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.deleteGroupBlog(
|
||||
pub_data, COMMENTS_NODE_URL_1, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
return d.addCallback(self.assertEqual, None)
|
||||
|
||||
def test_update_group_blog(self):
|
||||
pub_data = (SERVICE, NODE_ID, ITEM_ID_1)
|
||||
new_text = "silfu23RFWUP)IWNOEIOEFÖ"
|
||||
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.updateGroupBlog(
|
||||
pub_data, COMMENTS_NODE_URL_1, new_text, {}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
return d.addCallback(
|
||||
lambda items: self.assertEqual(
|
||||
"".join(items[0].entry.title.children), new_text
|
||||
)
|
||||
)
|
||||
|
||||
def test_send_group_blog_comment(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.items(SERVICE, NODE_ID)
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.sendGroupBlogComment(
|
||||
COMMENTS_NODE_URL_1, "test", {}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
return d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
|
||||
def test_get_group_blogs(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogs(PUBLISHER, profile_key=C.PROFILE[0])
|
||||
)
|
||||
result = (
|
||||
[ITEM_DATA_1()],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_no_count(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogs(
|
||||
PUBLISHER, count_comments=False, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[ITEM_DATA_1(DO_NOT_COUNT_COMMENTS)],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_with_i_ds(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogs(
|
||||
PUBLISHER, [ITEM_ID_1], profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[ITEM_DATA_1()],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_with_rsm(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogs(
|
||||
PUBLISHER, rsm_data={"max_": 1}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[ITEM_DATA_1()],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_with_comments(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1])
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogsWithComments(
|
||||
PUBLISHER, [], profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[
|
||||
(
|
||||
ITEM_DATA_1(1),
|
||||
(
|
||||
[COMMENT_DATA_1],
|
||||
{
|
||||
"count": "1",
|
||||
"index": "0",
|
||||
"first": COMMENT_ID_1,
|
||||
"last": COMMENT_ID_1,
|
||||
},
|
||||
),
|
||||
)
|
||||
],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_with_comments_2(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogsWithComments(
|
||||
PUBLISHER, [], profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[
|
||||
(
|
||||
ITEM_DATA_1(2),
|
||||
(
|
||||
[COMMENT_DATA_1, COMMENT_DATA_2],
|
||||
{
|
||||
"count": "2",
|
||||
"index": "0",
|
||||
"first": COMMENT_ID_1,
|
||||
"last": COMMENT_ID_2,
|
||||
},
|
||||
),
|
||||
)
|
||||
],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blogs_atom(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogsAtom(
|
||||
PUBLISHER, {"max_": 1}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
|
||||
def cb(atom):
|
||||
self.assertIsInstance(atom, str)
|
||||
self.assertTrue(atom.startswith('<?xml version="1.0" encoding="utf-8"?>'))
|
||||
|
||||
return d.addCallback(cb)
|
||||
|
||||
def test_get_massive_group_blogs(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getMassiveGroupBlogs(
|
||||
"JID", [jid.JID(PUBLISHER)], {"max_": 1}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = {
|
||||
PUBLISHER: (
|
||||
[ITEM_DATA_1()],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
}
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(clean)
|
||||
d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_massive_group_blogs_with_comments(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getMassiveGroupBlogs(
|
||||
"JID", [jid.JID(PUBLISHER)], {"max_": 1}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = {
|
||||
PUBLISHER: (
|
||||
[ITEM_DATA_1(2)],
|
||||
{"count": "1", "index": "0", "first": ITEM_ID_1, "last": ITEM_ID_1},
|
||||
)
|
||||
}
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(clean)
|
||||
d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_get_group_blog_comments(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1])
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.getGroupBlogComments(
|
||||
SERVICE, COMMENTS_NODE_ID_1, {"max_": 1}, profile_key=C.PROFILE[0]
|
||||
)
|
||||
)
|
||||
result = (
|
||||
[COMMENT_DATA_1],
|
||||
{"count": "1", "index": "0", "first": COMMENT_ID_1, "last": COMMENT_ID_1},
|
||||
)
|
||||
return d.addCallback(self.assertEqual, result)
|
||||
|
||||
def test_subscribe_group_blog(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.plugin.subscribeGroupBlog(PUBLISHER, profile_key=C.PROFILE[0])
|
||||
return d.addCallback(self.assertEqual, None)
|
||||
|
||||
def test_massive_subscribe_group_blogs(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
d = self.plugin.massiveSubscribeGroupBlogs(
|
||||
"JID", [jid.JID(PUBLISHER)], profile_key=C.PROFILE[0]
|
||||
)
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@subscriptions@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(clean)
|
||||
return d.addCallback(self.assertEqual, None)
|
||||
|
||||
def test_delete_all_group_blogs(self):
|
||||
"""Delete our main node and associated comments node"""
|
||||
self._initialise(C.PROFILE[0])
|
||||
self.host.profiles[C.PROFILE[0]].roster.add_item(jid.JID(OTHER_PUBLISHER))
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(SERVICE, OTHER_NODE_ID, [ITEM_2])
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_2, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(lambda __: self.plugin.deleteAllGroupBlogs(C.PROFILE[0]))
|
||||
d.addCallback(clean)
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
return d
|
||||
|
||||
def test_delete_all_group_blogs_comments(self):
|
||||
"""Delete the comments we posted on other node's"""
|
||||
self._initialise(C.PROFILE[0])
|
||||
self.host.profiles[C.PROFILE[0]].roster.add_item(jid.JID(OTHER_PUBLISHER))
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(SERVICE, OTHER_NODE_ID, [ITEM_2])
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_2, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(lambda __: self.plugin.deleteAllGroupBlogsComments(C.PROFILE[0]))
|
||||
d.addCallback(clean)
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
return d
|
||||
|
||||
def test_delete_all_group_blogs_and_comments(self):
|
||||
self._initialise(C.PROFILE[0])
|
||||
self.host.profiles[C.PROFILE[0]].roster.add_item(jid.JID(OTHER_PUBLISHER))
|
||||
d = self.psclient.publish(SERVICE, NODE_ID, [ITEM_1])
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_1, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(SERVICE, OTHER_NODE_ID, [ITEM_2])
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.psclient.publish(
|
||||
SERVICE, COMMENTS_NODE_ID_2, [COMMENT_1, COMMENT_2]
|
||||
)
|
||||
)
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 2))
|
||||
|
||||
def clean(res):
|
||||
del self.host.plugins["XEP-0060"].node_cache[
|
||||
C.PROFILE[0] + "@found@" + SERVICE
|
||||
]
|
||||
return res
|
||||
|
||||
d.addCallback(
|
||||
lambda __: self.plugin.deleteAllGroupBlogsAndComments(C.PROFILE[0])
|
||||
)
|
||||
d.addCallback(clean)
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_1))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, OTHER_NODE_ID))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 1))
|
||||
d.addCallback(lambda __: self.psclient.items(SERVICE, COMMENTS_NODE_ID_2))
|
||||
d.addCallback(lambda items: self.assertEqual(len(items), 0))
|
||||
return d
|
||||
518
libervia/backend/test/test_plugin_misc_radiocol.py
Normal file
518
libervia/backend/test/test_plugin_misc_radiocol.py
Normal file
|
|
@ -0,0 +1,518 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009, 2010, 2011, 2012, 2013 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Tests for the plugin radiocol """
|
||||
|
||||
from libervia.backend.core import exceptions
|
||||
from libervia.backend.test import helpers, helpers_plugins
|
||||
from libervia.backend.plugins import plugin_misc_radiocol as plugin
|
||||
from libervia.backend.plugins import plugin_misc_room_game as plugin_room_game
|
||||
from .constants import Const
|
||||
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from twisted.words.xish import domish
|
||||
from twisted.internet import reactor
|
||||
from twisted.internet import defer
|
||||
from twisted.python.failure import Failure
|
||||
from twisted.trial.unittest import SkipTest
|
||||
|
||||
try:
|
||||
from mutagen.oggvorbis import OggVorbis
|
||||
from mutagen.mp3 import MP3
|
||||
from mutagen.easyid3 import EasyID3
|
||||
from mutagen.id3 import ID3NoHeaderError
|
||||
except ImportError:
|
||||
raise exceptions.MissingModule(
|
||||
"Missing module Mutagen, please download/install from https://bitbucket.org/lazka/mutagen"
|
||||
)
|
||||
|
||||
import uuid
|
||||
import os
|
||||
import copy
|
||||
import shutil
|
||||
|
||||
|
||||
ROOM_JID = JID(Const.MUC_STR[0])
|
||||
PROFILE = Const.PROFILE[0]
|
||||
REFEREE_FULL = JID(ROOM_JID.userhost() + "/" + Const.JID[0].user)
|
||||
PLAYERS_INDICES = [0, 1, 3] # referee included
|
||||
OTHER_PROFILES = [Const.PROFILE[1], Const.PROFILE[3]]
|
||||
OTHER_PLAYERS = [Const.JID[1], Const.JID[3]]
|
||||
|
||||
|
||||
class RadiocolTest(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
|
||||
def reinit(self):
|
||||
self.host.reinit()
|
||||
self.host.plugins["ROOM-GAME"] = plugin_room_game.RoomGame(self.host)
|
||||
self.plugin = plugin.Radiocol(self.host) # must be init after ROOM-GAME
|
||||
self.plugin.testing = True
|
||||
self.plugin_0045 = self.host.plugins["XEP-0045"] = helpers_plugins.FakeXEP_0045(
|
||||
self.host
|
||||
)
|
||||
self.plugin_0249 = self.host.plugins["XEP-0249"] = helpers_plugins.FakeXEP_0249(
|
||||
self.host
|
||||
)
|
||||
for profile in Const.PROFILE:
|
||||
self.host.get_client(profile) # init self.host.profiles[profile]
|
||||
self.songs = []
|
||||
self.playlist = []
|
||||
self.sound_dir = self.host.memory.config_get("", "media_dir") + "/test/sound/"
|
||||
try:
|
||||
for filename in os.listdir(self.sound_dir):
|
||||
if filename.endswith(".ogg") or filename.endswith(".mp3"):
|
||||
self.songs.append(filename)
|
||||
except OSError:
|
||||
raise SkipTest("The sound samples in sat_media/test/sound were not found")
|
||||
|
||||
def _build_players(self, players=[]):
|
||||
"""@return: the "started" content built with the given players"""
|
||||
content = "<started"
|
||||
if not players:
|
||||
content += "/>"
|
||||
else:
|
||||
content += ">"
|
||||
for i in range(0, len(players)):
|
||||
content += "<player index='%s'>%s</player>" % (i, players[i])
|
||||
content += "</started>"
|
||||
return content
|
||||
|
||||
def _expected_message(self, to_jid, type_, content):
|
||||
"""
|
||||
@param to_jid: recipient full jid
|
||||
@param type_: message type ('normal' or 'groupchat')
|
||||
@param content: content as unicode or list of domish elements
|
||||
@return: the message XML built from the given recipient, message type and content
|
||||
"""
|
||||
if isinstance(content, list):
|
||||
new_content = copy.deepcopy(content)
|
||||
for element in new_content:
|
||||
if not element.hasAttribute("xmlns"):
|
||||
element["xmlns"] = ""
|
||||
content = "".join([element.toXml() for element in new_content])
|
||||
return "<message to='%s' type='%s'><%s xmlns='%s'>%s</%s></message>" % (
|
||||
to_jid.full(),
|
||||
type_,
|
||||
plugin.RADIOC_TAG,
|
||||
plugin.NC_RADIOCOL,
|
||||
content,
|
||||
plugin.RADIOC_TAG,
|
||||
)
|
||||
|
||||
def _reject_song_cb(self, profile_index):
|
||||
"""Check if the message "song_rejected" has been sent by the referee
|
||||
and process the command with the profile of the uploader
|
||||
@param profile_index: uploader's profile"""
|
||||
sent = self.host.get_sent_message(0)
|
||||
content = "<song_rejected xmlns='' reason='Too many songs in queue'/>"
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(),
|
||||
self._expected_message(
|
||||
JID(
|
||||
ROOM_JID.userhost()
|
||||
+ "/"
|
||||
+ self.plugin_0045.get_nick(0, profile_index),
|
||||
"normal",
|
||||
content,
|
||||
)
|
||||
),
|
||||
)
|
||||
self._room_game_cmd(
|
||||
sent, ["radiocol_song_rejected", ROOM_JID.full(), "Too many songs in queue"]
|
||||
)
|
||||
|
||||
def _no_upload_cb(self):
|
||||
"""Check if the message "no_upload" has been sent by the referee
|
||||
and process the command with the profiles of each room users"""
|
||||
sent = self.host.get_sent_message(0)
|
||||
content = "<no_upload xmlns=''/>"
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(), self._expected_message(ROOM_JID, "groupchat", content)
|
||||
)
|
||||
self._room_game_cmd(sent, ["radiocol_no_upload", ROOM_JID.full()])
|
||||
|
||||
def _upload_ok_cb(self):
|
||||
"""Check if the message "upload_ok" has been sent by the referee
|
||||
and process the command with the profiles of each room users"""
|
||||
sent = self.host.get_sent_message(0)
|
||||
content = "<upload_ok xmlns=''/>"
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(), self._expected_message(ROOM_JID, "groupchat", content)
|
||||
)
|
||||
self._room_game_cmd(sent, ["radiocol_upload_ok", ROOM_JID.full()])
|
||||
|
||||
def _preload_cb(self, attrs, profile_index):
|
||||
"""Check if the message "preload" has been sent by the referee
|
||||
and process the command with the profiles of each room users
|
||||
@param attrs: information dict about the song
|
||||
@param profile_index: profile index of the uploader
|
||||
"""
|
||||
sent = self.host.get_sent_message(0)
|
||||
attrs["sender"] = self.plugin_0045.get_nick(0, profile_index)
|
||||
radiocol_elt = next(domish.generateElementsNamed(sent.elements(), "radiocol"))
|
||||
preload_elt = next(domish.generateElementsNamed(
|
||||
radiocol_elt.elements(), "preload"
|
||||
))
|
||||
attrs["timestamp"] = preload_elt["timestamp"] # we could not guess it...
|
||||
content = "<preload xmlns='' %s/>" % " ".join(
|
||||
["%s='%s'" % (attr, attrs[attr]) for attr in attrs]
|
||||
)
|
||||
if sent.hasAttribute("from"):
|
||||
del sent["from"]
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(), self._expected_message(ROOM_JID, "groupchat", content)
|
||||
)
|
||||
self._room_game_cmd(
|
||||
sent,
|
||||
[
|
||||
"radiocol_preload",
|
||||
ROOM_JID.full(),
|
||||
attrs["timestamp"],
|
||||
attrs["filename"],
|
||||
attrs["title"],
|
||||
attrs["artist"],
|
||||
attrs["album"],
|
||||
attrs["sender"],
|
||||
],
|
||||
)
|
||||
|
||||
def _play_next_song_cb(self):
|
||||
"""Check if the message "play" has been sent by the referee
|
||||
and process the command with the profiles of each room users"""
|
||||
sent = self.host.get_sent_message(0)
|
||||
filename = self.playlist.pop(0)
|
||||
content = "<play xmlns='' filename='%s' />" % filename
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(), self._expected_message(ROOM_JID, "groupchat", content)
|
||||
)
|
||||
self._room_game_cmd(sent, ["radiocol_play", ROOM_JID.full(), filename])
|
||||
|
||||
game_data = self.plugin.games[ROOM_JID]
|
||||
if len(game_data["queue"]) == plugin.QUEUE_LIMIT - 1:
|
||||
self._upload_ok_cb()
|
||||
|
||||
def _add_song_cb(self, d, filepath, profile_index):
|
||||
"""Check if the message "song_added" has been sent by the uploader
|
||||
and process the command with the profile of the referee
|
||||
@param d: deferred value or failure got from self.plugin.radiocol_song_added
|
||||
@param filepath: full path to the sound file
|
||||
@param profile_index: the profile index of the uploader
|
||||
"""
|
||||
if isinstance(d, Failure):
|
||||
self.fail("OGG or MP3 song could not be added!")
|
||||
|
||||
game_data = self.plugin.games[ROOM_JID]
|
||||
|
||||
# this is copied from the plugin
|
||||
if filepath.lower().endswith(".mp3"):
|
||||
actual_song = MP3(filepath)
|
||||
try:
|
||||
song = EasyID3(filepath)
|
||||
|
||||
class Info(object):
|
||||
def __init__(self, length):
|
||||
self.length = length
|
||||
|
||||
song.info = Info(actual_song.info.length)
|
||||
except ID3NoHeaderError:
|
||||
song = actual_song
|
||||
else:
|
||||
song = OggVorbis(filepath)
|
||||
|
||||
attrs = {
|
||||
"filename": os.path.basename(filepath),
|
||||
"title": song.get("title", ["Unknown"])[0],
|
||||
"artist": song.get("artist", ["Unknown"])[0],
|
||||
"album": song.get("album", ["Unknown"])[0],
|
||||
"length": str(song.info.length),
|
||||
}
|
||||
self.assertEqual(game_data["to_delete"][attrs["filename"]], filepath)
|
||||
|
||||
content = "<song_added xmlns='' %s/>" % " ".join(
|
||||
["%s='%s'" % (attr, attrs[attr]) for attr in attrs]
|
||||
)
|
||||
sent = self.host.get_sent_message(profile_index)
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(), self._expected_message(REFEREE_FULL, "normal", content)
|
||||
)
|
||||
|
||||
reject_song = len(game_data["queue"]) >= plugin.QUEUE_LIMIT
|
||||
no_upload = len(game_data["queue"]) + 1 >= plugin.QUEUE_LIMIT
|
||||
play_next = (
|
||||
not game_data["playing"]
|
||||
and len(game_data["queue"]) + 1 == plugin.QUEUE_TO_START
|
||||
)
|
||||
|
||||
self._room_game_cmd(sent, profile_index) # queue unchanged or +1
|
||||
if reject_song:
|
||||
self._reject_song_cb(profile_index)
|
||||
return
|
||||
if no_upload:
|
||||
self._no_upload_cb()
|
||||
self._preload_cb(attrs, profile_index)
|
||||
self.playlist.append(attrs["filename"])
|
||||
if play_next:
|
||||
self._play_next_song_cb() # queue -1
|
||||
|
||||
def _room_game_cmd(self, sent, from_index=0, call=[]):
|
||||
"""Process a command. It is also possible to call this method as
|
||||
_room_game_cmd(sent, call) instead of _room_game_cmd(sent, from_index, call).
|
||||
If from index is a list, it is assumed that it is containing the value
|
||||
for call and from_index will take its default value.
|
||||
@param sent: the sent message that we need to process
|
||||
@param from_index: index of the message sender
|
||||
@param call: list containing the name of the expected bridge call
|
||||
followed by its arguments, or empty list if no call is expected
|
||||
"""
|
||||
if isinstance(from_index, list):
|
||||
call = from_index
|
||||
from_index = 0
|
||||
|
||||
sent["from"] = ROOM_JID.full() + "/" + self.plugin_0045.get_nick(0, from_index)
|
||||
recipient = JID(sent["to"]).resource
|
||||
|
||||
# The message could have been sent to a room user (room_jid + '/' + nick),
|
||||
# but when it is received, the 'to' attribute of the message has been
|
||||
# changed to the recipient own JID. We need to simulate that here.
|
||||
if recipient:
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
sent["to"] = (
|
||||
Const.JID_STR[0]
|
||||
if recipient == room.nick
|
||||
else room.roster[recipient].entity.full()
|
||||
)
|
||||
|
||||
for index in range(0, len(Const.PROFILE)):
|
||||
nick = self.plugin_0045.get_nick(0, index)
|
||||
if nick:
|
||||
if not recipient or nick == recipient:
|
||||
if call and (
|
||||
self.plugin.is_player(ROOM_JID, nick)
|
||||
or call[0] == "radiocol_started"
|
||||
):
|
||||
args = copy.deepcopy(call)
|
||||
args.append(Const.PROFILE[index])
|
||||
self.host.bridge.expect_call(*args)
|
||||
self.plugin.room_game_cmd(sent, Const.PROFILE[index])
|
||||
|
||||
def _sync_cb(self, sync_data, profile_index):
|
||||
"""Synchronize one player when he joins a running game.
|
||||
@param sync_data: result from self.plugin.getSyncData
|
||||
@param profile_index: index of the profile to be synchronized
|
||||
"""
|
||||
for nick in sync_data:
|
||||
expected = self._expected_message(
|
||||
JID(ROOM_JID.userhost() + "/" + nick), "normal", sync_data[nick]
|
||||
)
|
||||
sent = self.host.get_sent_message(0)
|
||||
self.assert_equal_xml(sent.toXml(), expected)
|
||||
for elt in sync_data[nick]:
|
||||
if elt.name == "preload":
|
||||
self.host.bridge.expect_call(
|
||||
"radiocol_preload",
|
||||
ROOM_JID.full(),
|
||||
elt["timestamp"],
|
||||
elt["filename"],
|
||||
elt["title"],
|
||||
elt["artist"],
|
||||
elt["album"],
|
||||
elt["sender"],
|
||||
Const.PROFILE[profile_index],
|
||||
)
|
||||
elif elt.name == "play":
|
||||
self.host.bridge.expect_call(
|
||||
"radiocol_play",
|
||||
ROOM_JID.full(),
|
||||
elt["filename"],
|
||||
Const.PROFILE[profile_index],
|
||||
)
|
||||
elif elt.name == "no_upload":
|
||||
self.host.bridge.expect_call(
|
||||
"radiocol_no_upload", ROOM_JID.full(), Const.PROFILE[profile_index]
|
||||
)
|
||||
sync_data[nick]
|
||||
self._room_game_cmd(sent, [])
|
||||
|
||||
def _join_room(self, room, nicks, player_index, sync=True):
|
||||
"""Make a player join a room and update the list of nicks
|
||||
@param room: wokkel.muc.Room instance from the referee perspective
|
||||
@param nicks: list of the players which will be updated
|
||||
@param player_index: profile index of the new player
|
||||
@param sync: set to True to synchronize data
|
||||
"""
|
||||
user_nick = self.plugin_0045.join_room(0, player_index)
|
||||
self.plugin.user_joined_trigger(room, room.roster[user_nick], PROFILE)
|
||||
if player_index not in PLAYERS_INDICES:
|
||||
# this user is actually not a player
|
||||
self.assertFalse(self.plugin.is_player(ROOM_JID, user_nick))
|
||||
to_jid, type_ = (JID(ROOM_JID.userhost() + "/" + user_nick), "normal")
|
||||
else:
|
||||
# this user is a player
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, user_nick))
|
||||
nicks.append(user_nick)
|
||||
to_jid, type_ = (ROOM_JID, "groupchat")
|
||||
|
||||
# Check that the message "players" has been sent by the referee
|
||||
expected = self._expected_message(to_jid, type_, self._build_players(nicks))
|
||||
sent = self.host.get_sent_message(0)
|
||||
self.assert_equal_xml(sent.toXml(), expected)
|
||||
|
||||
# Process the command with the profiles of each room users
|
||||
self._room_game_cmd(
|
||||
sent,
|
||||
[
|
||||
"radiocol_started",
|
||||
ROOM_JID.full(),
|
||||
REFEREE_FULL.full(),
|
||||
nicks,
|
||||
[plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT],
|
||||
],
|
||||
)
|
||||
|
||||
if sync:
|
||||
self._sync_cb(self.plugin._get_sync_data(ROOM_JID, [user_nick]), player_index)
|
||||
|
||||
def _leave_room(self, room, nicks, player_index):
|
||||
"""Make a player leave a room and update the list of nicks
|
||||
@param room: wokkel.muc.Room instance from the referee perspective
|
||||
@param nicks: list of the players which will be updated
|
||||
@param player_index: profile index of the new player
|
||||
"""
|
||||
user_nick = self.plugin_0045.get_nick(0, player_index)
|
||||
user = room.roster[user_nick]
|
||||
self.plugin_0045.leave_room(0, player_index)
|
||||
self.plugin.user_left_trigger(room, user, PROFILE)
|
||||
nicks.remove(user_nick)
|
||||
|
||||
def _upload_song(self, song_index, profile_index):
|
||||
"""Upload the song of index song_index (modulo self.songs size) from the profile of index profile_index.
|
||||
|
||||
@param song_index: index of the song or None to test with non existing file
|
||||
@param profile_index: index of the uploader's profile
|
||||
"""
|
||||
if song_index is None:
|
||||
dst_filepath = str(uuid.uuid1())
|
||||
expect_io_error = True
|
||||
else:
|
||||
song_index = song_index % len(self.songs)
|
||||
src_filename = self.songs[song_index]
|
||||
dst_filepath = "/tmp/%s%s" % (uuid.uuid1(), os.path.splitext(src_filename)[1])
|
||||
shutil.copy(self.sound_dir + src_filename, dst_filepath)
|
||||
expect_io_error = False
|
||||
|
||||
try:
|
||||
d = self.plugin.radiocol_song_added(
|
||||
REFEREE_FULL, dst_filepath, Const.PROFILE[profile_index]
|
||||
)
|
||||
except IOError:
|
||||
self.assertTrue(expect_io_error)
|
||||
return
|
||||
|
||||
self.assertFalse(expect_io_error)
|
||||
cb = lambda defer: self._add_song_cb(defer, dst_filepath, profile_index)
|
||||
|
||||
def eb(failure):
|
||||
if not isinstance(failure, Failure):
|
||||
self.fail("Adding a song which is not OGG nor MP3 should fail!")
|
||||
self.assertEqual(failure.value.__class__, exceptions.DataError)
|
||||
|
||||
if src_filename.endswith(".ogg") or src_filename.endswith(".mp3"):
|
||||
d.addCallbacks(cb, cb)
|
||||
else:
|
||||
d.addCallbacks(eb, eb)
|
||||
|
||||
def test_init(self):
|
||||
self.reinit()
|
||||
self.assertEqual(self.plugin.invite_mode, self.plugin.FROM_PLAYERS)
|
||||
self.assertEqual(self.plugin.wait_mode, self.plugin.FOR_NONE)
|
||||
self.assertEqual(self.plugin.join_mode, self.plugin.INVITED)
|
||||
self.assertEqual(self.plugin.ready_mode, self.plugin.FORCE)
|
||||
|
||||
def test_game(self):
|
||||
self.reinit()
|
||||
|
||||
# create game
|
||||
self.plugin.prepare_room(OTHER_PLAYERS, ROOM_JID, PROFILE)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
nicks = [self.plugin_0045.get_nick(0, 0)]
|
||||
|
||||
sent = self.host.get_sent_message(0)
|
||||
self.assert_equal_xml(
|
||||
sent.toXml(),
|
||||
self._expected_message(ROOM_JID, "groupchat", self._build_players(nicks)),
|
||||
)
|
||||
self._room_game_cmd(
|
||||
sent,
|
||||
[
|
||||
"radiocol_started",
|
||||
ROOM_JID.full(),
|
||||
REFEREE_FULL.full(),
|
||||
nicks,
|
||||
[plugin.QUEUE_TO_START, plugin.QUEUE_LIMIT],
|
||||
],
|
||||
)
|
||||
|
||||
self._join_room(room, nicks, 1) # player joins
|
||||
self._join_room(room, nicks, 4) # user not playing joins
|
||||
|
||||
song_index = 0
|
||||
self._upload_song(
|
||||
song_index, 0
|
||||
) # ogg or mp3 file should exist in sat_media/test/song
|
||||
self._upload_song(None, 0) # non existing file
|
||||
|
||||
# another songs are added by Const.JID[1] until the radio starts + 1 to fill the queue
|
||||
# when the first song starts + 1 to be rejected because the queue is full
|
||||
for song_index in range(1, plugin.QUEUE_TO_START + 1):
|
||||
self._upload_song(song_index, 1)
|
||||
|
||||
self.plugin.play_next(Const.MUC[0], PROFILE) # simulate the end of the first song
|
||||
self._play_next_song_cb()
|
||||
self._upload_song(
|
||||
song_index, 1
|
||||
) # now the song is accepted and the queue is full again
|
||||
|
||||
self._join_room(room, nicks, 3) # new player joins
|
||||
|
||||
self.plugin.play_next(Const.MUC[0], PROFILE) # the second song finishes
|
||||
self._play_next_song_cb()
|
||||
self._upload_song(0, 3) # the player who recently joined re-upload the first file
|
||||
|
||||
self._leave_room(room, nicks, 1) # one player leaves
|
||||
self._join_room(room, nicks, 1) # and join again
|
||||
|
||||
self.plugin.play_next(Const.MUC[0], PROFILE) # empty the queue
|
||||
self._play_next_song_cb()
|
||||
self.plugin.play_next(Const.MUC[0], PROFILE)
|
||||
self._play_next_song_cb()
|
||||
|
||||
for filename in self.playlist:
|
||||
self.plugin.delete_file("/tmp/" + filename)
|
||||
|
||||
return defer.succeed(None)
|
||||
|
||||
def tearDown(self, *args, **kwargs):
|
||||
"""Clean the reactor"""
|
||||
helpers.SatTestCase.tearDown(self, *args, **kwargs)
|
||||
for delayed_call in reactor.getDelayedCalls():
|
||||
delayed_call.cancel()
|
||||
654
libervia/backend/test/test_plugin_misc_room_game.py
Normal file
654
libervia/backend/test/test_plugin_misc_room_game.py
Normal file
|
|
@ -0,0 +1,654 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Tests for the plugin room game (base class for MUC games) """
|
||||
|
||||
from libervia.backend.core.i18n import _
|
||||
from .constants import Const
|
||||
from libervia.backend.test import helpers, helpers_plugins
|
||||
from libervia.backend.plugins import plugin_misc_room_game as plugin
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from wokkel.muc import User
|
||||
|
||||
from logging import WARNING
|
||||
|
||||
# Data used for test initialization
|
||||
NAMESERVICE = "http://www.goffi.org/protocol/dummy"
|
||||
TAG = "dummy"
|
||||
PLUGIN_INFO = {
|
||||
"name": "Dummy plugin",
|
||||
"import_name": "DUMMY",
|
||||
"type": "MISC",
|
||||
"protocols": [],
|
||||
"dependencies": [],
|
||||
"main": "Dummy",
|
||||
"handler": "no", # handler MUST be "no" (dynamic inheritance)
|
||||
"description": _("""Dummy plugin to test room game"""),
|
||||
}
|
||||
|
||||
ROOM_JID = JID(Const.MUC_STR[0])
|
||||
PROFILE = Const.PROFILE[0]
|
||||
OTHER_PROFILE = Const.PROFILE[1]
|
||||
|
||||
|
||||
class RoomGameTest(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
|
||||
def reinit(self, game_init={}, player_init={}):
|
||||
self.host.reinit()
|
||||
self.plugin = plugin.RoomGame(self.host)
|
||||
self.plugin._init_(
|
||||
self.host, PLUGIN_INFO, (NAMESERVICE, TAG), game_init, player_init
|
||||
)
|
||||
self.plugin_0045 = self.host.plugins["XEP-0045"] = helpers_plugins.FakeXEP_0045(
|
||||
self.host
|
||||
)
|
||||
self.plugin_0249 = self.host.plugins["XEP-0249"] = helpers_plugins.FakeXEP_0249(
|
||||
self.host
|
||||
)
|
||||
for profile in Const.PROFILE:
|
||||
self.host.get_client(profile) # init self.host.profiles[profile]
|
||||
|
||||
def init_game(self, muc_index, user_index):
|
||||
self.plugin_0045.join_room(user_index, muc_index)
|
||||
self.plugin._init_game(JID(Const.MUC_STR[muc_index]), Const.JID[user_index].user)
|
||||
|
||||
def _expected_message(self, to, type_, tag, players=[]):
|
||||
content = "<%s" % tag
|
||||
if not players:
|
||||
content += "/>"
|
||||
else:
|
||||
content += ">"
|
||||
for i in range(0, len(players)):
|
||||
content += "<player index='%s'>%s</player>" % (i, players[i])
|
||||
content += "</%s>" % tag
|
||||
return "<message to='%s' type='%s'><%s xmlns='%s'>%s</dummy></message>" % (
|
||||
to.full(),
|
||||
type_,
|
||||
TAG,
|
||||
NAMESERVICE,
|
||||
content,
|
||||
)
|
||||
|
||||
def test_create_or_invite_solo(self):
|
||||
self.reinit()
|
||||
self.plugin_0045.join_room(0, 0)
|
||||
self.plugin._create_or_invite(self.plugin_0045.get_room(0, 0), [], Const.PROFILE[0])
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
|
||||
def test_create_or_invite_multi_not_waiting(self):
|
||||
self.reinit()
|
||||
self.plugin_0045.join_room(0, 0)
|
||||
other_players = [Const.JID[1], Const.JID[2]]
|
||||
self.plugin._create_or_invite(
|
||||
self.plugin_0045.get_room(0, 0), other_players, Const.PROFILE[0]
|
||||
)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
|
||||
def test_create_or_invite_multi_waiting(self):
|
||||
self.reinit(player_init={"score": 0})
|
||||
self.plugin_0045.join_room(0, 0)
|
||||
other_players = [Const.JID[1], Const.JID[2]]
|
||||
self.plugin._create_or_invite(
|
||||
self.plugin_0045.get_room(0, 0), other_players, Const.PROFILE[0]
|
||||
)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, False))
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True))
|
||||
|
||||
def test_init_game(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.assertTrue(self.plugin.is_referee(ROOM_JID, Const.JID[0].user))
|
||||
self.assertEqual([], self.plugin.games[ROOM_JID]["players"])
|
||||
|
||||
def test_check_join_auth(self):
|
||||
self.reinit()
|
||||
check = lambda value: getattr(self, "assert%s" % value)(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[0], Const.JID[0].user)
|
||||
)
|
||||
check(False)
|
||||
# to test the "invited" mode, the referee must be different than the user to test
|
||||
self.init_game(0, 1)
|
||||
self.plugin.join_mode = self.plugin.ALL
|
||||
check(True)
|
||||
self.plugin.join_mode = self.plugin.INVITED
|
||||
check(False)
|
||||
self.plugin.invitations[ROOM_JID] = [(None, [Const.JID[0].userhostJID()])]
|
||||
check(True)
|
||||
self.plugin.join_mode = self.plugin.NONE
|
||||
check(False)
|
||||
self.plugin.games[ROOM_JID]["players"].append(Const.JID[0].user)
|
||||
check(True)
|
||||
|
||||
def test_update_players(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], [])
|
||||
self.plugin._update_players(ROOM_JID, [], True, Const.PROFILE[0])
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], [])
|
||||
self.plugin._update_players(ROOM_JID, ["user1"], True, Const.PROFILE[0])
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], ["user1"])
|
||||
self.plugin._update_players(ROOM_JID, ["user2", "user3"], True, Const.PROFILE[0])
|
||||
self.assertEqual(
|
||||
self.plugin.games[ROOM_JID]["players"], ["user1", "user2", "user3"]
|
||||
)
|
||||
self.plugin._update_players(
|
||||
ROOM_JID, ["user2", "user3"], True, Const.PROFILE[0]
|
||||
) # should not be stored twice
|
||||
self.assertEqual(
|
||||
self.plugin.games[ROOM_JID]["players"], ["user1", "user2", "user3"]
|
||||
)
|
||||
|
||||
def test_synchronize_room(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.plugin._synchronize_room(ROOM_JID, [Const.MUC[0]], Const.PROFILE[0])
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "players", []),
|
||||
)
|
||||
self.plugin.games[ROOM_JID]["players"].append("test1")
|
||||
self.plugin._synchronize_room(ROOM_JID, [Const.MUC[0]], Const.PROFILE[0])
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "players", ["test1"]),
|
||||
)
|
||||
self.plugin.games[ROOM_JID]["started"] = True
|
||||
self.plugin.games[ROOM_JID]["players"].append("test2")
|
||||
self.plugin._synchronize_room(ROOM_JID, [Const.MUC[0]], Const.PROFILE[0])
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "started", ["test1", "test2"]),
|
||||
)
|
||||
self.plugin.games[ROOM_JID]["players"].append("test3")
|
||||
self.plugin.games[ROOM_JID]["players"].append("test4")
|
||||
user1 = JID(ROOM_JID.userhost() + "/" + Const.JID[0].user)
|
||||
user2 = JID(ROOM_JID.userhost() + "/" + Const.JID[1].user)
|
||||
self.plugin._synchronize_room(ROOM_JID, [user1, user2], Const.PROFILE[0])
|
||||
self.assert_equal_xml(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(
|
||||
user1, "normal", "started", ["test1", "test2", "test3", "test4"]
|
||||
),
|
||||
)
|
||||
self.assert_equal_xml(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(
|
||||
user2, "normal", "started", ["test1", "test2", "test3", "test4"]
|
||||
),
|
||||
)
|
||||
|
||||
def test_invite_players(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.plugin_0045.join_room(0, 1)
|
||||
self.assertEqual(self.plugin.invitations[ROOM_JID], [])
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
nicks = self.plugin._invite_players(
|
||||
room, [Const.JID[1], Const.JID[2]], Const.JID[0].user, Const.PROFILE[0]
|
||||
)
|
||||
self.assertEqual(
|
||||
self.plugin.invitations[ROOM_JID][0][1],
|
||||
[Const.JID[1].userhostJID(), Const.JID[2].userhostJID()],
|
||||
)
|
||||
# the following assertion is True because Const.JID[1] and Const.JID[2] have the same userhost
|
||||
self.assertEqual(nicks, [Const.JID[1].user, Const.JID[2].user])
|
||||
|
||||
nicks = self.plugin._invite_players(
|
||||
room, [Const.JID[1], Const.JID[3]], Const.JID[0].user, Const.PROFILE[0]
|
||||
)
|
||||
self.assertEqual(
|
||||
self.plugin.invitations[ROOM_JID][1][1],
|
||||
[Const.JID[1].userhostJID(), Const.JID[3].userhostJID()],
|
||||
)
|
||||
# this time Const.JID[1] and Const.JID[3] have the same user but the host differs
|
||||
self.assertEqual(nicks, [Const.JID[1].user])
|
||||
|
||||
def test_check_invite_auth(self):
|
||||
def check(value, index):
|
||||
nick = self.plugin_0045.get_nick(0, index)
|
||||
getattr(self, "assert%s" % value)(
|
||||
self.plugin._check_invite_auth(ROOM_JID, nick)
|
||||
)
|
||||
|
||||
self.reinit()
|
||||
|
||||
for mode in [
|
||||
self.plugin.FROM_ALL,
|
||||
self.plugin.FROM_NONE,
|
||||
self.plugin.FROM_REFEREE,
|
||||
self.plugin.FROM_PLAYERS,
|
||||
]:
|
||||
self.plugin.invite_mode = mode
|
||||
check(True, 0)
|
||||
|
||||
self.init_game(0, 0)
|
||||
self.plugin.invite_mode = self.plugin.FROM_ALL
|
||||
check(True, 0)
|
||||
check(True, 1)
|
||||
self.plugin.invite_mode = self.plugin.FROM_NONE
|
||||
check(True, 0) # game initialized but not started yet, referee can invite
|
||||
check(False, 1)
|
||||
self.plugin.invite_mode = self.plugin.FROM_REFEREE
|
||||
check(True, 0)
|
||||
check(False, 1)
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.games[ROOM_JID]["players"].append(user_nick)
|
||||
self.plugin.invite_mode = self.plugin.FROM_PLAYERS
|
||||
check(True, 0)
|
||||
check(True, 1)
|
||||
check(False, 2)
|
||||
|
||||
def test_is_referee(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.assertTrue(self.plugin.is_referee(ROOM_JID, self.plugin_0045.get_nick(0, 0)))
|
||||
self.assertFalse(self.plugin.is_referee(ROOM_JID, self.plugin_0045.get_nick(0, 1)))
|
||||
|
||||
def test_is_player(self):
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, self.plugin_0045.get_nick(0, 0)))
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.games[ROOM_JID]["players"].append(user_nick)
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, user_nick))
|
||||
self.assertFalse(self.plugin.is_player(ROOM_JID, self.plugin_0045.get_nick(0, 2)))
|
||||
|
||||
def test_check_wait_auth(self):
|
||||
def check(value, other_players, confirmed, rest):
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
self.assertEqual(
|
||||
(value, confirmed, rest), self.plugin._check_wait_auth(room, other_players)
|
||||
)
|
||||
|
||||
self.reinit()
|
||||
self.init_game(0, 0)
|
||||
other_players = [Const.JID[1], Const.JID[3]]
|
||||
self.plugin.wait_mode = self.plugin.FOR_NONE
|
||||
check(True, [], [], [])
|
||||
check(
|
||||
True, [Const.JID[0]], [], [Const.JID[0]]
|
||||
) # getRoomNickOfUser checks for the other users only
|
||||
check(True, other_players, [], other_players)
|
||||
self.plugin.wait_mode = self.plugin.FOR_ALL
|
||||
check(True, [], [], [])
|
||||
check(False, [Const.JID[0]], [], [Const.JID[0]])
|
||||
check(False, other_players, [], other_players)
|
||||
self.plugin_0045.join_room(0, 1)
|
||||
check(False, other_players, [], other_players)
|
||||
self.plugin_0045.join_room(0, 4)
|
||||
check(
|
||||
False,
|
||||
other_players,
|
||||
[self.plugin_0045.get_nick_of_user(0, 1, 0)],
|
||||
[Const.JID[3]],
|
||||
)
|
||||
self.plugin_0045.join_room(0, 3)
|
||||
check(
|
||||
True,
|
||||
other_players,
|
||||
[
|
||||
self.plugin_0045.get_nick_of_user(0, 1, 0),
|
||||
self.plugin_0045.get_nick_of_user(0, 3, 0),
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
other_players = [Const.JID[1], Const.JID[3], Const.JID[2]]
|
||||
# the following assertion is True because Const.JID[1] and Const.JID[2] have the same userhost
|
||||
check(
|
||||
True,
|
||||
other_players,
|
||||
[
|
||||
self.plugin_0045.get_nick_of_user(0, 1, 0),
|
||||
self.plugin_0045.get_nick_of_user(0, 3, 0),
|
||||
self.plugin_0045.get_nick_of_user(0, 2, 0),
|
||||
],
|
||||
[],
|
||||
)
|
||||
|
||||
def test_prepare_room_trivial(self):
|
||||
self.reinit()
|
||||
other_players = []
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
self.assertTrue(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[0], Const.JID[0].user)
|
||||
)
|
||||
self.assertTrue(self.plugin._check_invite_auth(ROOM_JID, Const.JID[0].user))
|
||||
self.assertEqual((True, [], []), self.plugin._check_wait_auth(ROOM_JID, []))
|
||||
self.assertTrue(self.plugin.is_referee(ROOM_JID, Const.JID[0].user))
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, Const.JID[0].user))
|
||||
self.assertEqual(
|
||||
(False, True), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
|
||||
def test_prepare_room_invite(self):
|
||||
self.reinit()
|
||||
other_players = [Const.JID[1], Const.JID[2]]
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
self.assertTrue(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[1], Const.JID[1].user)
|
||||
)
|
||||
self.assertFalse(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[3], Const.JID[3].user)
|
||||
)
|
||||
self.assertFalse(self.plugin._check_invite_auth(ROOM_JID, Const.JID[1].user))
|
||||
self.assertEqual(
|
||||
(True, [], other_players), self.plugin._check_wait_auth(room, other_players)
|
||||
)
|
||||
|
||||
player2_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, room.roster[player2_nick], PROFILE)
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, player2_nick))
|
||||
self.assertTrue(self.plugin._check_invite_auth(ROOM_JID, player2_nick))
|
||||
self.assertFalse(self.plugin.is_referee(ROOM_JID, player2_nick))
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, player2_nick))
|
||||
self.assertTrue(
|
||||
self.plugin.is_player(ROOM_JID, self.plugin_0045.get_nick_of_user(0, 2, 0))
|
||||
)
|
||||
self.assertFalse(self.plugin.is_player(ROOM_JID, "xxx"))
|
||||
self.assertEqual(
|
||||
(False, False),
|
||||
self.plugin._check_create_game_and_init(ROOM_JID, Const.PROFILE[1]),
|
||||
)
|
||||
|
||||
def test_prepare_room_score_1(self):
|
||||
self.reinit(player_init={"score": 0})
|
||||
other_players = [Const.JID[1], Const.JID[2]]
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True))
|
||||
self.assertTrue(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[1], Const.JID[1].user)
|
||||
)
|
||||
self.assertFalse(
|
||||
self.plugin._check_join_auth(ROOM_JID, Const.JID[3], Const.JID[3].user)
|
||||
)
|
||||
self.assertFalse(self.plugin._check_invite_auth(ROOM_JID, Const.JID[1].user))
|
||||
self.assertEqual(
|
||||
(False, [], other_players), self.plugin._check_wait_auth(room, other_players)
|
||||
)
|
||||
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, room.roster[user_nick], PROFILE)
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, user_nick))
|
||||
self.assertFalse(self.plugin._check_invite_auth(ROOM_JID, user_nick))
|
||||
self.assertFalse(self.plugin.is_referee(ROOM_JID, user_nick))
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, user_nick))
|
||||
# the following assertion is True because Const.JID[1] and Const.JID[2] have the same userhost
|
||||
self.assertTrue(
|
||||
self.plugin.is_player(ROOM_JID, self.plugin_0045.get_nick_of_user(0, 2, 0))
|
||||
)
|
||||
# the following assertion is True because Const.JID[1] nick in the room is equal to Const.JID[3].user
|
||||
self.assertTrue(self.plugin.is_player(ROOM_JID, Const.JID[3].user))
|
||||
# but Const.JID[3] is actually not in the room
|
||||
self.assertEqual(self.plugin_0045.get_nick_of_user(0, 3, 0), None)
|
||||
self.assertEqual(
|
||||
(True, False), self.plugin._check_create_game_and_init(ROOM_JID, Const.PROFILE[0])
|
||||
)
|
||||
|
||||
def test_prepare_room_score_2(self):
|
||||
self.reinit(player_init={"score": 0})
|
||||
other_players = [Const.JID[1], Const.JID[4]]
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, room.roster[user_nick], PROFILE)
|
||||
self.assertEqual(
|
||||
(True, False), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
user_nick = self.plugin_0045.join_room(0, 4)
|
||||
self.plugin.user_joined_trigger(room, room.roster[user_nick], PROFILE)
|
||||
self.assertEqual(
|
||||
(False, True), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
|
||||
def test_user_joined_trigger(self):
|
||||
self.reinit(player_init={"xxx": "xyz"})
|
||||
other_players = [Const.JID[1], Const.JID[3]]
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
nicks = [self.plugin_0045.get_nick(0, 0)]
|
||||
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "players", nicks),
|
||||
)
|
||||
self.assertTrue(len(self.plugin.invitations[ROOM_JID]) == 1)
|
||||
|
||||
# wrong profile
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
room = self.plugin_0045.get_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[1]), OTHER_PROFILE)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message(0), None
|
||||
) # no new message has been sent
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True)) # game not started
|
||||
|
||||
# referee profile, user is allowed, wait for one more
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[1]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "players", nicks),
|
||||
)
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True)) # game not started
|
||||
|
||||
# referee profile, user is not allowed
|
||||
user_nick = self.plugin_0045.join_room(0, 4)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[4]), PROFILE)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(
|
||||
JID(ROOM_JID.userhost() + "/" + user_nick), "normal", "players", nicks
|
||||
),
|
||||
)
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True)) # game not started
|
||||
|
||||
# referee profile, user is allowed, everybody here
|
||||
user_nick = self.plugin_0045.join_room(0, 3)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[3]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "started", nicks),
|
||||
)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True)) # game started
|
||||
self.assertTrue(len(self.plugin.invitations[ROOM_JID]) == 0)
|
||||
|
||||
# wait for none
|
||||
self.reinit()
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
self.assertNotEqual(self.host.get_sent_message(0), None) # init messages
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
nicks = [self.plugin_0045.get_nick(0, 0)]
|
||||
user_nick = self.plugin_0045.join_room(0, 3)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[3]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "started", nicks),
|
||||
)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
|
||||
def test_user_left_trigger(self):
|
||||
self.reinit(player_init={"xxx": "xyz"})
|
||||
other_players = [Const.JID[1], Const.JID[3], Const.JID[4]]
|
||||
self.plugin.prepare_room(other_players, ROOM_JID, PROFILE)
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
nicks = [self.plugin_0045.get_nick(0, 0)]
|
||||
self.assertEqual(
|
||||
self.plugin.invitations[ROOM_JID][0][1],
|
||||
[
|
||||
Const.JID[1].userhostJID(),
|
||||
Const.JID[3].userhostJID(),
|
||||
Const.JID[4].userhostJID(),
|
||||
],
|
||||
)
|
||||
|
||||
# one user joins
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[1]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
|
||||
# the user leaves
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
room = self.plugin_0045.get_room(0, 1)
|
||||
# to not call self.plugin_0045.leave_room(0, 1) here, we are testing the trigger with a wrong profile
|
||||
self.plugin.user_left_trigger(
|
||||
room, User(user_nick, Const.JID[1]), Const.PROFILE[1]
|
||||
) # not the referee
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
room = self.plugin_0045.get_room(0, 0)
|
||||
user_nick = self.plugin_0045.leave_room(0, 1)
|
||||
self.plugin.user_left_trigger(
|
||||
room, User(user_nick, Const.JID[1]), PROFILE
|
||||
) # referee
|
||||
nicks.pop()
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
|
||||
# all the users join
|
||||
user_nick = self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[1]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
user_nick = self.plugin_0045.join_room(0, 3)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[3]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
user_nick = self.plugin_0045.join_room(0, 4)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[4]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
self.assertTrue(len(self.plugin.invitations[ROOM_JID]) == 0)
|
||||
|
||||
# one user leaves
|
||||
user_nick = self.plugin_0045.leave_room(0, 4)
|
||||
self.plugin.user_left_trigger(room, User(user_nick, Const.JID[4]), PROFILE)
|
||||
nicks.pop()
|
||||
self.assertEqual(
|
||||
self.plugin.invitations[ROOM_JID][0][1], [Const.JID[4].userhostJID()]
|
||||
)
|
||||
|
||||
# another leaves
|
||||
user_nick = self.plugin_0045.leave_room(0, 3)
|
||||
self.plugin.user_left_trigger(room, User(user_nick, Const.JID[3]), PROFILE)
|
||||
nicks.pop()
|
||||
self.assertEqual(
|
||||
self.plugin.invitations[ROOM_JID][0][1],
|
||||
[Const.JID[4].userhostJID(), Const.JID[3].userhostJID()],
|
||||
)
|
||||
|
||||
# they can join again
|
||||
user_nick = self.plugin_0045.join_room(0, 3)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[3]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
user_nick = self.plugin_0045.join_room(0, 4)
|
||||
self.plugin.user_joined_trigger(room, User(user_nick, Const.JID[4]), PROFILE)
|
||||
nicks.append(user_nick)
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
self.assertTrue(len(self.plugin.invitations[ROOM_JID]) == 0)
|
||||
|
||||
def test_check_create_game_and_init(self):
|
||||
self.reinit()
|
||||
helpers.mute_logging()
|
||||
self.assertEqual(
|
||||
(False, False), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
helpers.unmute_logging()
|
||||
|
||||
nick = self.plugin_0045.join_room(0, 0)
|
||||
self.assertEqual(
|
||||
(True, False), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, False))
|
||||
self.assertFalse(self.plugin._game_exists(ROOM_JID, True))
|
||||
self.assertTrue(self.plugin.is_referee(ROOM_JID, nick))
|
||||
|
||||
helpers.mute_logging()
|
||||
self.assertEqual(
|
||||
(False, False), self.plugin._check_create_game_and_init(ROOM_JID, OTHER_PROFILE)
|
||||
)
|
||||
helpers.unmute_logging()
|
||||
|
||||
self.plugin_0045.join_room(0, 1)
|
||||
self.assertEqual(
|
||||
(False, False), self.plugin._check_create_game_and_init(ROOM_JID, OTHER_PROFILE)
|
||||
)
|
||||
|
||||
self.plugin.create_game(ROOM_JID, [Const.JID[1]], PROFILE)
|
||||
self.assertEqual(
|
||||
(False, True), self.plugin._check_create_game_and_init(ROOM_JID, PROFILE)
|
||||
)
|
||||
self.assertEqual(
|
||||
(False, False), self.plugin._check_create_game_and_init(ROOM_JID, OTHER_PROFILE)
|
||||
)
|
||||
|
||||
def test_create_game(self):
|
||||
|
||||
self.reinit(player_init={"xxx": "xyz"})
|
||||
nicks = []
|
||||
for i in [0, 1, 3, 4]:
|
||||
nicks.append(self.plugin_0045.join_room(0, i))
|
||||
|
||||
# game not exists
|
||||
self.plugin.create_game(ROOM_JID, nicks, PROFILE)
|
||||
self.assertTrue(self.plugin._game_exists(ROOM_JID, True))
|
||||
self.assertEqual(self.plugin.games[ROOM_JID]["players"], nicks)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "started", nicks),
|
||||
)
|
||||
for nick in nicks:
|
||||
self.assertEqual("init", self.plugin.games[ROOM_JID]["status"][nick])
|
||||
self.assertEqual(
|
||||
self.plugin.player_init, self.plugin.games[ROOM_JID]["players_data"][nick]
|
||||
)
|
||||
self.plugin.games[ROOM_JID]["players_data"][nick]["xxx"] = nick
|
||||
for nick in nicks:
|
||||
# checks that a copy of self.player_init has been done and not a reference
|
||||
self.assertEqual(
|
||||
nick, self.plugin.games[ROOM_JID]["players_data"][nick]["xxx"]
|
||||
)
|
||||
|
||||
# game exists, current profile is referee
|
||||
self.reinit(player_init={"xxx": "xyz"})
|
||||
self.init_game(0, 0)
|
||||
self.plugin.games[ROOM_JID]["started"] = True
|
||||
self.plugin.create_game(ROOM_JID, nicks, PROFILE)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message_xml(0),
|
||||
self._expected_message(ROOM_JID, "groupchat", "started", nicks),
|
||||
)
|
||||
|
||||
# game exists, current profile is not referee
|
||||
self.reinit(player_init={"xxx": "xyz"})
|
||||
self.init_game(0, 0)
|
||||
self.plugin.games[ROOM_JID]["started"] = True
|
||||
self.plugin_0045.join_room(0, 1)
|
||||
self.plugin.create_game(ROOM_JID, nicks, OTHER_PROFILE)
|
||||
self.assertEqual(
|
||||
self.host.get_sent_message(0), None
|
||||
) # no sync message has been sent by other_profile
|
||||
115
libervia/backend/test/test_plugin_misc_text_syntaxes.py
Normal file
115
libervia/backend/test/test_plugin_misc_text_syntaxes.py
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin text syntaxes tests """
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins import plugin_misc_text_syntaxes
|
||||
from twisted.trial.unittest import SkipTest
|
||||
import re
|
||||
import importlib
|
||||
|
||||
|
||||
class SanitisationTest(helpers.SatTestCase):
|
||||
|
||||
EVIL_HTML1 = """
|
||||
<html>
|
||||
<head>
|
||||
<script type="text/javascript" src="evil-site"></script>
|
||||
<link rel="alternate" type="text/rss" src="evil-rss">
|
||||
<style>
|
||||
body {background-image: url(javascript:do_evil)};
|
||||
div {color: expression(evil)};
|
||||
</style>
|
||||
</head>
|
||||
<body onload="evil_function()">
|
||||
<!-- I am interpreted for EVIL! -->
|
||||
<a href="javascript:evil_function()">a link</a>
|
||||
<a href="#" onclick="evil_function()">another link</a>
|
||||
<p onclick="evil_function()">a paragraph</p>
|
||||
<div style="display: none">secret EVIL!</div>
|
||||
<object> of EVIL! </object>
|
||||
<iframe src="evil-site"></iframe>
|
||||
<form action="evil-site">
|
||||
Password: <input type="password" name="password">
|
||||
</form>
|
||||
<blink>annoying EVIL!</blink>
|
||||
<a href="evil-site">spam spam SPAM!</a>
|
||||
<image src="evil!">
|
||||
</body>
|
||||
</html>""" # example from lxml: /usr/share/doc/python-lxml-doc/html/lxmlhtml.html#cleaning-up-html
|
||||
|
||||
EVIL_HTML2 = """<p style='display: None; test: blah; background: url(: alert()); color: blue;'>test <strong>retest</strong><br><span style="background-color: (alert('bouh')); titi; color: #cf2828; font-size: 3px; direction: !important; color: red; color: red !important; font-size: 100px !important; font-size: 100px ! important; font-size: 100%; font-size: 100ox; font-size: 100px; font-size: 100;;;; font-size: 100 %; color: 100 px 1.7em; color: rgba(0, 0, 0, 0.1); color: rgb(35,79,255); background-color: no-repeat; background-color: :alert(1); color: (alert('XSS')); color: (window.location='http://example.org/'); color: url(:window.location='http://example.org/'); "> toto </span></p>"""
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
importlib.reload(plugin_misc_text_syntaxes) # reload the plugin to avoid conflict error
|
||||
self.text_syntaxes = plugin_misc_text_syntaxes.TextSyntaxes(self.host)
|
||||
|
||||
def test_xhtml_sanitise(self):
|
||||
expected = """<div>
|
||||
<style>/* deleted */</style>
|
||||
<body>
|
||||
<a href="">a link</a>
|
||||
<a href="#">another link</a>
|
||||
<p>a paragraph</p>
|
||||
<div style="">secret EVIL!</div>
|
||||
of EVIL!
|
||||
Password:
|
||||
annoying EVIL!
|
||||
<a href="evil-site">spam spam SPAM!</a>
|
||||
<img src="evil!">
|
||||
</img></body>
|
||||
</div>"""
|
||||
|
||||
d = self.text_syntaxes.clean_xhtml(self.EVIL_HTML1)
|
||||
d.addCallback(self.assert_equal_xml, expected, ignore_blank=True)
|
||||
return d
|
||||
|
||||
def test_styles_sanitise(self):
|
||||
expected = """<p style="color: blue">test <strong>retest</strong><br/><span style="color: #cf2828; font-size: 3px; color: red; color: red !important; font-size: 100px !important; font-size: 100%; font-size: 100px; font-size: 100; font-size: 100 %; color: rgba(0, 0, 0, 0.1); color: rgb(35,79,255); background-color: no-repeat"> toto </span></p>"""
|
||||
|
||||
d = self.text_syntaxes.clean_xhtml(self.EVIL_HTML2)
|
||||
d.addCallback(self.assert_equal_xml, expected)
|
||||
return d
|
||||
|
||||
def test_html2text(self):
|
||||
"""Check that html2text is not inserting \n in the middle of that link.
|
||||
By default lines are truncated after the 79th characters."""
|
||||
source = '<img src="http://sat.goffi.org/static/images/screenshots/libervia/libervia_discussions.png" alt="sat"/>'
|
||||
expected = ""
|
||||
try:
|
||||
d = self.text_syntaxes.convert(
|
||||
source,
|
||||
self.text_syntaxes.SYNTAX_XHTML,
|
||||
self.text_syntaxes.SYNTAX_MARKDOWN,
|
||||
)
|
||||
except plugin_misc_text_syntaxes.UnknownSyntax:
|
||||
raise SkipTest("Markdown syntax is not available.")
|
||||
d.addCallback(self.assertEqual, expected)
|
||||
return d
|
||||
|
||||
def test_remove_xhtml_markups(self):
|
||||
expected = """ a link another link a paragraph secret EVIL! of EVIL! Password: annoying EVIL! spam spam SPAM! """
|
||||
result = self.text_syntaxes._remove_markups(self.EVIL_HTML1)
|
||||
self.assertEqual(re.sub(r"\s+", " ", result).rstrip(), expected.rstrip())
|
||||
|
||||
expected = """test retest toto"""
|
||||
result = self.text_syntaxes._remove_markups(self.EVIL_HTML2)
|
||||
self.assertEqual(re.sub(r"\s+", " ", result).rstrip(), expected.rstrip())
|
||||
211
libervia/backend/test/test_plugin_xep_0033.py
Normal file
211
libervia/backend/test/test_plugin_xep_0033.py
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin extended addressing stanzas """
|
||||
|
||||
from .constants import Const
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins import plugin_xep_0033 as plugin
|
||||
from libervia.backend.core.exceptions import CancelError
|
||||
from twisted.internet import defer
|
||||
from wokkel.generic import parseXml
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
|
||||
PROFILE_INDEX = 0
|
||||
PROFILE = Const.PROFILE[PROFILE_INDEX]
|
||||
JID_STR_FROM = Const.JID_STR[1]
|
||||
JID_STR_TO = Const.PROFILE_DICT[PROFILE].host
|
||||
JID_STR_X_TO = Const.JID_STR[0]
|
||||
JID_STR_X_CC = Const.JID_STR[1]
|
||||
JID_STR_X_BCC = Const.JID_STR[2]
|
||||
|
||||
ADDRS = ("to", JID_STR_X_TO, "cc", JID_STR_X_CC, "bcc", JID_STR_X_BCC)
|
||||
|
||||
|
||||
class XEP_0033Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = plugin.XEP_0033(self.host)
|
||||
|
||||
def test_message_received(self):
|
||||
self.host.memory.reinit()
|
||||
xml = """
|
||||
<message type="chat" from="%s" to="%s" id="test_1">
|
||||
<body>test</body>
|
||||
<addresses xmlns='http://jabber.org/protocol/address'>
|
||||
<address type='to' jid='%s'/>
|
||||
<address type='cc' jid='%s'/>
|
||||
<address type='bcc' jid='%s'/>
|
||||
</addresses>
|
||||
</message>
|
||||
""" % (
|
||||
JID_STR_FROM,
|
||||
JID_STR_TO,
|
||||
JID_STR_X_TO,
|
||||
JID_STR_X_CC,
|
||||
JID_STR_X_BCC,
|
||||
)
|
||||
stanza = parseXml(xml.encode("utf-8"))
|
||||
treatments = defer.Deferred()
|
||||
self.plugin.message_received_trigger(
|
||||
self.host.get_client(PROFILE), stanza, treatments
|
||||
)
|
||||
data = {"extra": {}}
|
||||
|
||||
def cb(data):
|
||||
expected = ("to", JID_STR_X_TO, "cc", JID_STR_X_CC, "bcc", JID_STR_X_BCC)
|
||||
msg = "Expected: %s\nGot: %s" % (expected, data["extra"]["addresses"])
|
||||
self.assertEqual(
|
||||
data["extra"]["addresses"], "%s:%s\n%s:%s\n%s:%s\n" % expected, msg
|
||||
)
|
||||
|
||||
treatments.addCallback(cb)
|
||||
return treatments.callback(data)
|
||||
|
||||
def _get_mess_data(self):
|
||||
mess_data = {
|
||||
"to": JID(JID_STR_TO),
|
||||
"type": "chat",
|
||||
"message": "content",
|
||||
"extra": {},
|
||||
}
|
||||
mess_data["extra"]["address"] = "%s:%s\n%s:%s\n%s:%s\n" % ADDRS
|
||||
original_stanza = """
|
||||
<message type="chat" from="%s" to="%s" id="test_1">
|
||||
<body>content</body>
|
||||
</message>
|
||||
""" % (
|
||||
JID_STR_FROM,
|
||||
JID_STR_TO,
|
||||
)
|
||||
mess_data["xml"] = parseXml(original_stanza.encode("utf-8"))
|
||||
return mess_data
|
||||
|
||||
def _assert_addresses(self, mess_data):
|
||||
"""The mess_data that we got here has been modified by self.plugin.messageSendTrigger,
|
||||
check that the addresses element has been added to the stanza."""
|
||||
expected = self._get_mess_data()["xml"]
|
||||
addresses_extra = (
|
||||
"""
|
||||
<addresses xmlns='http://jabber.org/protocol/address'>
|
||||
<address type='%s' jid='%s'/>
|
||||
<address type='%s' jid='%s'/>
|
||||
<address type='%s' jid='%s'/>
|
||||
</addresses>"""
|
||||
% ADDRS
|
||||
)
|
||||
addresses_element = parseXml(addresses_extra.encode("utf-8"))
|
||||
expected.addChild(addresses_element)
|
||||
self.assert_equal_xml(
|
||||
mess_data["xml"].toXml().encode("utf-8"), expected.toXml().encode("utf-8")
|
||||
)
|
||||
|
||||
def _check_sent_and_stored(self):
|
||||
"""Check that all the recipients got their messages and that the history has been filled.
|
||||
/!\ see the comments in XEP_0033.send_and_store_message"""
|
||||
sent = []
|
||||
stored = []
|
||||
d_list = []
|
||||
|
||||
def cb(entities, to_jid):
|
||||
if host in entities:
|
||||
if (
|
||||
host not in sent
|
||||
): # send the message to the entity offering the feature
|
||||
sent.append(host)
|
||||
stored.append(host)
|
||||
stored.append(to_jid) # store in history for each recipient
|
||||
else: # feature not supported, use normal behavior
|
||||
sent.append(to_jid)
|
||||
stored.append(to_jid)
|
||||
helpers.unmute_logging()
|
||||
|
||||
for to_s in (JID_STR_X_TO, JID_STR_X_CC, JID_STR_X_BCC):
|
||||
to_jid = JID(to_s)
|
||||
host = JID(to_jid.host)
|
||||
helpers.mute_logging()
|
||||
d = self.host.find_features_set([plugin.NS_ADDRESS], jid_=host, profile=PROFILE)
|
||||
d.addCallback(cb, to_jid)
|
||||
d_list.append(d)
|
||||
|
||||
def cb_list(__):
|
||||
msg = "/!\ see the comments in XEP_0033.send_and_store_message"
|
||||
sent_recipients = [
|
||||
JID(elt["to"]) for elt in self.host.get_sent_messages(PROFILE_INDEX)
|
||||
]
|
||||
self.assert_equal_unsorted_list(sent_recipients, sent, msg)
|
||||
self.assert_equal_unsorted_list(self.host.stored_messages, stored, msg)
|
||||
|
||||
return defer.DeferredList(d_list).addCallback(cb_list)
|
||||
|
||||
def _trigger(self, data):
|
||||
"""Execute self.plugin.messageSendTrigger with a different logging
|
||||
level to not pollute the output, then check that the plugin did its
|
||||
job. It should abort sending the message or add the extended
|
||||
addressing information to the stanza.
|
||||
@param data: the data to be processed by self.plugin.messageSendTrigger
|
||||
"""
|
||||
pre_treatments = defer.Deferred()
|
||||
post_treatments = defer.Deferred()
|
||||
helpers.mute_logging()
|
||||
self.plugin.messageSendTrigger(
|
||||
self.host.get_client[PROFILE], data, pre_treatments, post_treatments
|
||||
)
|
||||
post_treatments.callback(data)
|
||||
helpers.unmute_logging()
|
||||
post_treatments.addCallbacks(
|
||||
self._assert_addresses, lambda failure: failure.trap(CancelError)
|
||||
)
|
||||
return post_treatments
|
||||
|
||||
def test_message_send_trigger_feature_not_supported(self):
|
||||
# feature is not supported, abort the message
|
||||
self.host.memory.reinit()
|
||||
data = self._get_mess_data()
|
||||
return self._trigger(data)
|
||||
|
||||
def test_message_send_trigger_feature_supported(self):
|
||||
# feature is supported by the main target server
|
||||
self.host.reinit()
|
||||
self.host.add_feature(JID(JID_STR_TO), plugin.NS_ADDRESS, PROFILE)
|
||||
data = self._get_mess_data()
|
||||
d = self._trigger(data)
|
||||
return d.addCallback(lambda __: self._check_sent_and_stored())
|
||||
|
||||
def test_message_send_trigger_feature_fully_supported(self):
|
||||
# feature is supported by all target servers
|
||||
self.host.reinit()
|
||||
self.host.add_feature(JID(JID_STR_TO), plugin.NS_ADDRESS, PROFILE)
|
||||
for dest in (JID_STR_X_TO, JID_STR_X_CC, JID_STR_X_BCC):
|
||||
self.host.add_feature(JID(JID(dest).host), plugin.NS_ADDRESS, PROFILE)
|
||||
data = self._get_mess_data()
|
||||
d = self._trigger(data)
|
||||
return d.addCallback(lambda __: self._check_sent_and_stored())
|
||||
|
||||
def test_message_send_trigger_fix_wrong_entity(self):
|
||||
# check that a wrong recipient entity is fixed by the backend
|
||||
self.host.reinit()
|
||||
self.host.add_feature(JID(JID_STR_TO), plugin.NS_ADDRESS, PROFILE)
|
||||
for dest in (JID_STR_X_TO, JID_STR_X_CC, JID_STR_X_BCC):
|
||||
self.host.add_feature(JID(JID(dest).host), plugin.NS_ADDRESS, PROFILE)
|
||||
data = self._get_mess_data()
|
||||
data["to"] = JID(JID_STR_X_TO)
|
||||
d = self._trigger(data)
|
||||
return d.addCallback(lambda __: self._check_sent_and_stored())
|
||||
104
libervia/backend/test/test_plugin_xep_0085.py
Normal file
104
libervia/backend/test/test_plugin_xep_0085.py
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin chat states notification tests """
|
||||
|
||||
from .constants import Const
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.core.constants import Const as C
|
||||
from libervia.backend.plugins import plugin_xep_0085 as plugin
|
||||
from copy import deepcopy
|
||||
from twisted.internet import defer
|
||||
from wokkel.generic import parseXml
|
||||
|
||||
|
||||
class XEP_0085Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = plugin.XEP_0085(self.host)
|
||||
self.host.memory.param_set(
|
||||
plugin.PARAM_NAME,
|
||||
True,
|
||||
plugin.PARAM_KEY,
|
||||
C.NO_SECURITY_LIMIT,
|
||||
Const.PROFILE[0],
|
||||
)
|
||||
|
||||
def test_message_received(self):
|
||||
for state in plugin.CHAT_STATES:
|
||||
xml = """
|
||||
<message type="chat" from="%s" to="%s" id="test_1">
|
||||
%s
|
||||
<%s xmlns='%s'/>
|
||||
</message>
|
||||
""" % (
|
||||
Const.JID_STR[1],
|
||||
Const.JID_STR[0],
|
||||
"<body>test</body>" if state == "active" else "",
|
||||
state,
|
||||
plugin.NS_CHAT_STATES,
|
||||
)
|
||||
stanza = parseXml(xml.encode("utf-8"))
|
||||
self.host.bridge.expect_call(
|
||||
"chat_state_received", Const.JID_STR[1], state, Const.PROFILE[0]
|
||||
)
|
||||
self.plugin.message_received_trigger(
|
||||
self.host.get_client(Const.PROFILE[0]), stanza, None
|
||||
)
|
||||
|
||||
def test_message_send_trigger(self):
|
||||
def cb(data):
|
||||
xml = data["xml"].toXml().encode("utf-8")
|
||||
self.assert_equal_xml(xml, expected.toXml().encode("utf-8"))
|
||||
|
||||
d_list = []
|
||||
|
||||
for state in plugin.CHAT_STATES:
|
||||
mess_data = {
|
||||
"to": Const.JID[0],
|
||||
"type": "chat",
|
||||
"message": "content",
|
||||
"extra": {} if state == "active" else {"chat_state": state},
|
||||
}
|
||||
stanza = """
|
||||
<message type="chat" from="%s" to="%s" id="test_1">
|
||||
%s
|
||||
</message>
|
||||
""" % (
|
||||
Const.JID_STR[1],
|
||||
Const.JID_STR[0],
|
||||
("<body>%s</body>" % mess_data["message"]) if state == "active" else "",
|
||||
)
|
||||
mess_data["xml"] = parseXml(stanza.encode("utf-8"))
|
||||
expected = deepcopy(mess_data["xml"])
|
||||
expected.addElement(state, plugin.NS_CHAT_STATES)
|
||||
post_treatments = defer.Deferred()
|
||||
self.plugin.messageSendTrigger(
|
||||
self.host.get_client(Const.PROFILE[0]), mess_data, None, post_treatments
|
||||
)
|
||||
|
||||
post_treatments.addCallback(cb)
|
||||
post_treatments.callback(mess_data)
|
||||
d_list.append(post_treatments)
|
||||
|
||||
def cb_list(__): # cancel the timer to not block the process
|
||||
self.plugin.map[Const.PROFILE[0]][Const.JID[0]].timer.cancel()
|
||||
|
||||
return defer.DeferredList(d_list).addCallback(cb_list)
|
||||
67
libervia/backend/test/test_plugin_xep_0203.py
Normal file
67
libervia/backend/test/test_plugin_xep_0203.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin XEP-0203 """
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins.plugin_xep_0203 import XEP_0203
|
||||
from twisted.words.xish import domish
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from dateutil.tz import tzutc
|
||||
import datetime
|
||||
|
||||
NS_PUBSUB = "http://jabber.org/protocol/pubsub"
|
||||
|
||||
|
||||
class XEP_0203Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = XEP_0203(self.host)
|
||||
|
||||
def test_delay(self):
|
||||
delay_xml = """
|
||||
<delay xmlns='urn:xmpp:delay'
|
||||
from='capulet.com'
|
||||
stamp='2002-09-10T23:08:25Z'>
|
||||
Offline Storage
|
||||
</delay>
|
||||
"""
|
||||
message_xml = (
|
||||
"""
|
||||
<message
|
||||
from='romeo@montague.net/orchard'
|
||||
to='juliet@capulet.com'
|
||||
type='chat'>
|
||||
<body>text</body>
|
||||
%s
|
||||
</message>
|
||||
"""
|
||||
% delay_xml
|
||||
)
|
||||
|
||||
parent = domish.Element((None, "message"))
|
||||
parent["from"] = "romeo@montague.net/orchard"
|
||||
parent["to"] = "juliet@capulet.com"
|
||||
parent["type"] = "chat"
|
||||
parent.addElement("body", None, "text")
|
||||
stamp = datetime.datetime(2002, 9, 10, 23, 8, 25, tzinfo=tzutc())
|
||||
elt = self.plugin.delay(stamp, JID("capulet.com"), "Offline Storage", parent)
|
||||
self.assert_equal_xml(elt.toXml(), delay_xml, True)
|
||||
self.assert_equal_xml(parent.toXml(), message_xml, True)
|
||||
126
libervia/backend/test/test_plugin_xep_0277.py
Normal file
126
libervia/backend/test/test_plugin_xep_0277.py
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin XEP-0277 tests """
|
||||
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins import plugin_xep_0277
|
||||
from libervia.backend.plugins import plugin_xep_0060
|
||||
from libervia.backend.plugins import plugin_misc_text_syntaxes
|
||||
from libervia.backend.tools.xml_tools import ElementParser
|
||||
from wokkel.pubsub import NS_PUBSUB
|
||||
import importlib
|
||||
|
||||
|
||||
class XEP_0277Test(helpers.SatTestCase):
|
||||
|
||||
PUBSUB_ENTRY_1 = (
|
||||
"""
|
||||
<item id="c745a688-9b02-11e3-a1a3-c0143dd4fe51">
|
||||
<entry xmlns="%s">
|
||||
<title type="text"><span>titre</span></title>
|
||||
<id>c745a688-9b02-11e3-a1a3-c0143dd4fe51</id>
|
||||
<updated>2014-02-21T16:16:39+02:00</updated>
|
||||
<published>2014-02-21T16:16:38+02:00</published>
|
||||
<content type="text"><p>contenu</p>texte sans balise<p>autre contenu</p></content>
|
||||
<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>contenu</p>texte sans balise<p>autre contenu</p></div></content>
|
||||
<author>
|
||||
<name>test1@souliane.org</name>
|
||||
</author>
|
||||
</entry>
|
||||
</item>
|
||||
"""
|
||||
% plugin_xep_0277.NS_ATOM
|
||||
)
|
||||
|
||||
PUBSUB_ENTRY_2 = (
|
||||
"""
|
||||
<item id="c745a688-9b02-11e3-a1a3-c0143dd4fe51">
|
||||
<entry xmlns='%s'>
|
||||
<title type="text"><div>titre</div></title>
|
||||
<title type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><div style="background-image: url('xxx');">titre</div></div></title>
|
||||
<id>c745a688-9b02-11e3-a1a3-c0143dd4fe51</id>
|
||||
<updated>2014-02-21T16:16:39+02:00</updated>
|
||||
<published>2014-02-21T16:16:38+02:00</published>
|
||||
<content type="text"><div><p>contenu</p>texte dans balise<p>autre contenu</p></div></content>
|
||||
<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>contenu</p>texte dans balise<p>autre contenu</p></div></content>
|
||||
<author>
|
||||
<name>test1@souliane.org</name>
|
||||
<nick>test1</nick>
|
||||
</author>
|
||||
</entry>
|
||||
</item>
|
||||
"""
|
||||
% plugin_xep_0277.NS_ATOM
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
|
||||
class XEP_0163(object):
|
||||
def __init__(self, host):
|
||||
pass
|
||||
|
||||
def add_pep_event(self, *args):
|
||||
pass
|
||||
|
||||
self.host.plugins["XEP-0060"] = plugin_xep_0060.XEP_0060(self.host)
|
||||
self.host.plugins["XEP-0163"] = XEP_0163(self.host)
|
||||
importlib.reload(plugin_misc_text_syntaxes) # reload the plugin to avoid conflict error
|
||||
self.host.plugins["TEXT_SYNTAXES"] = plugin_misc_text_syntaxes.TextSyntaxes(
|
||||
self.host
|
||||
)
|
||||
self.plugin = plugin_xep_0277.XEP_0277(self.host)
|
||||
|
||||
def test_item2mbdata_1(self):
|
||||
expected = {
|
||||
"id": "c745a688-9b02-11e3-a1a3-c0143dd4fe51",
|
||||
"atom_id": "c745a688-9b02-11e3-a1a3-c0143dd4fe51",
|
||||
"title": "<span>titre</span>",
|
||||
"updated": "1392992199.0",
|
||||
"published": "1392992198.0",
|
||||
"content": "<p>contenu</p>texte sans balise<p>autre contenu</p>",
|
||||
"content_xhtml": "<div><p>contenu</p>texte sans balise<p>autre contenu</p></div>",
|
||||
"author": "test1@souliane.org",
|
||||
}
|
||||
item_elt = (
|
||||
next(ElementParser()(self.PUBSUB_ENTRY_1, namespace=NS_PUBSUB).elements())
|
||||
)
|
||||
d = self.plugin.item2mbdata(item_elt)
|
||||
d.addCallback(self.assertEqual, expected)
|
||||
return d
|
||||
|
||||
def test_item2mbdata_2(self):
|
||||
expected = {
|
||||
"id": "c745a688-9b02-11e3-a1a3-c0143dd4fe51",
|
||||
"atom_id": "c745a688-9b02-11e3-a1a3-c0143dd4fe51",
|
||||
"title": "<div>titre</div>",
|
||||
"title_xhtml": '<div><div style="">titre</div></div>',
|
||||
"updated": "1392992199.0",
|
||||
"published": "1392992198.0",
|
||||
"content": "<div><p>contenu</p>texte dans balise<p>autre contenu</p></div>",
|
||||
"content_xhtml": "<div><p>contenu</p>texte dans balise<p>autre contenu</p></div>",
|
||||
"author": "test1@souliane.org",
|
||||
}
|
||||
item_elt = (
|
||||
next(ElementParser()(self.PUBSUB_ENTRY_2, namespace=NS_PUBSUB).elements())
|
||||
)
|
||||
d = self.plugin.item2mbdata(item_elt)
|
||||
d.addCallback(self.assertEqual, expected)
|
||||
return d
|
||||
89
libervia/backend/test/test_plugin_xep_0297.py
Normal file
89
libervia/backend/test/test_plugin_xep_0297.py
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin XEP-0297 """
|
||||
|
||||
from .constants import Const as C
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins.plugin_xep_0203 import XEP_0203
|
||||
from libervia.backend.plugins.plugin_xep_0297 import XEP_0297
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from dateutil.tz import tzutc
|
||||
import datetime
|
||||
from wokkel.generic import parseXml
|
||||
|
||||
|
||||
NS_PUBSUB = "http://jabber.org/protocol/pubsub"
|
||||
|
||||
|
||||
class XEP_0297Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = XEP_0297(self.host)
|
||||
self.host.plugins["XEP-0203"] = XEP_0203(self.host)
|
||||
|
||||
def test_delay(self):
|
||||
stanza = parseXml(
|
||||
"""
|
||||
<message from='juliet@capulet.lit/orchard'
|
||||
id='0202197'
|
||||
to='romeo@montague.lit'
|
||||
type='chat'>
|
||||
<body>Yet I should kill thee with much cherishing.</body>
|
||||
<mood xmlns='http://jabber.org/protocol/mood'>
|
||||
<amorous/>
|
||||
</mood>
|
||||
</message>
|
||||
""".encode(
|
||||
"utf-8"
|
||||
)
|
||||
)
|
||||
output = """
|
||||
<message to='mercutio@verona.lit' type='chat'>
|
||||
<body>A most courteous exposition!</body>
|
||||
<forwarded xmlns='urn:xmpp:forward:0'>
|
||||
<delay xmlns='urn:xmpp:delay' stamp='2010-07-10T23:08:25Z'/>
|
||||
<message from='juliet@capulet.lit/orchard'
|
||||
id='0202197'
|
||||
to='romeo@montague.lit'
|
||||
type='chat'
|
||||
xmlns='jabber:client'>
|
||||
<body>Yet I should kill thee with much cherishing.</body>
|
||||
<mood xmlns='http://jabber.org/protocol/mood'>
|
||||
<amorous/>
|
||||
</mood>
|
||||
</message>
|
||||
</forwarded>
|
||||
</message>
|
||||
"""
|
||||
stamp = datetime.datetime(2010, 7, 10, 23, 8, 25, tzinfo=tzutc())
|
||||
d = self.plugin.forward(
|
||||
stanza,
|
||||
JID("mercutio@verona.lit"),
|
||||
stamp,
|
||||
body="A most courteous exposition!",
|
||||
profile_key=C.PROFILE[0],
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(
|
||||
self.host.get_sent_message_xml(0), output, True
|
||||
)
|
||||
)
|
||||
return d
|
||||
314
libervia/backend/test/test_plugin_xep_0313.py
Normal file
314
libervia/backend/test/test_plugin_xep_0313.py
Normal file
|
|
@ -0,0 +1,314 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin XEP-0313 """
|
||||
|
||||
from .constants import Const as C
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins.plugin_xep_0313 import XEP_0313
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from twisted.words.xish import domish
|
||||
from wokkel.data_form import Field
|
||||
from dateutil.tz import tzutc
|
||||
import datetime
|
||||
|
||||
# TODO: change this when RSM and MAM are in wokkel
|
||||
from sat_tmp.wokkel.rsm import RSMRequest
|
||||
from sat_tmp.wokkel.mam import buildForm, MAMRequest
|
||||
|
||||
NS_PUBSUB = "http://jabber.org/protocol/pubsub"
|
||||
SERVICE = "sat-pubsub.tazar.int"
|
||||
SERVICE_JID = JID(SERVICE)
|
||||
|
||||
|
||||
class XEP_0313Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = XEP_0313(self.host)
|
||||
self.client = self.host.get_client(C.PROFILE[0])
|
||||
mam_client = self.plugin.get_handler(C.PROFILE[0])
|
||||
mam_client.makeConnection(self.host.get_client(C.PROFILE[0]).xmlstream)
|
||||
|
||||
def test_query_archive(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'/>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_pubsub(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1' node='fdp/submitted/capulet.lit/sonnets' />
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
d = self.plugin.queryArchive(
|
||||
self.client, MAMRequest(node="fdp/submitted/capulet.lit/sonnets"), SERVICE_JID
|
||||
)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_with(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field var='FORM_TYPE' type='hidden'>
|
||||
<value>urn:xmpp:mam:1</value>
|
||||
</field>
|
||||
<field var='with' type='jid-single'>
|
||||
<value>juliet@capulet.lit</value>
|
||||
</field>
|
||||
</x>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
form = buildForm(with_jid=JID("juliet@capulet.lit"))
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_start_end(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field var='FORM_TYPE' type='hidden'>
|
||||
<value>urn:xmpp:mam:1</value>
|
||||
</field>
|
||||
<field var='start' type='text-single'>
|
||||
<value>2010-06-07T00:00:00Z</value>
|
||||
</field>
|
||||
<field var='end' type='text-single'>
|
||||
<value>2010-07-07T13:23:54Z</value>
|
||||
</field>
|
||||
</x>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
start = datetime.datetime(2010, 6, 7, 0, 0, 0, tzinfo=tzutc())
|
||||
end = datetime.datetime(2010, 7, 7, 13, 23, 54, tzinfo=tzutc())
|
||||
form = buildForm(start=start, end=end)
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_start(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field var='FORM_TYPE' type='hidden'>
|
||||
<value>urn:xmpp:mam:1</value>
|
||||
</field>
|
||||
<field var='start' type='text-single'>
|
||||
<value>2010-08-07T00:00:00Z</value>
|
||||
</field>
|
||||
</x>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
start = datetime.datetime(2010, 8, 7, 0, 0, 0, tzinfo=tzutc())
|
||||
form = buildForm(start=start)
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_rsm(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field var='FORM_TYPE' type='hidden'>
|
||||
<value>urn:xmpp:mam:1</value>
|
||||
</field>
|
||||
<field var='start' type='text-single'>
|
||||
<value>2010-08-07T00:00:00Z</value>
|
||||
</field>
|
||||
</x>
|
||||
<set xmlns='http://jabber.org/protocol/rsm'>
|
||||
<max>10</max>
|
||||
</set>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
start = datetime.datetime(2010, 8, 7, 0, 0, 0, tzinfo=tzutc())
|
||||
form = buildForm(start=start)
|
||||
rsm = RSMRequest(max_=10)
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form, rsm), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_rsm_paging(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field var='FORM_TYPE' type='hidden'><value>urn:xmpp:mam:1</value></field>
|
||||
<field var='start' type='text-single'><value>2010-08-07T00:00:00Z</value></field>
|
||||
</x>
|
||||
<set xmlns='http://jabber.org/protocol/rsm'>
|
||||
<max>10</max>
|
||||
<after>09af3-cc343-b409f</after>
|
||||
</set>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
start = datetime.datetime(2010, 8, 7, 0, 0, 0, tzinfo=tzutc())
|
||||
form = buildForm(start=start)
|
||||
rsm = RSMRequest(max_=10, after="09af3-cc343-b409f")
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form, rsm), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_fields(self):
|
||||
xml = """
|
||||
<iq type='get' id="%s" to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'/>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
d = self.plugin.queryFields(self.client, SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_archive_fields(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<query xmlns='urn:xmpp:mam:1'>
|
||||
<x xmlns='jabber:x:data' type='submit'>
|
||||
<field type='hidden' var='FORM_TYPE'>
|
||||
<value>urn:xmpp:mam:1</value>
|
||||
</field>
|
||||
<field type='text-single' var='urn:example:xmpp:free-text-search'>
|
||||
<value>Where arth thou, my Juliet?</value>
|
||||
</field>
|
||||
<field type='text-single' var='urn:example:xmpp:stanza-content'>
|
||||
<value>{http://jabber.org/protocol/mood}mood/lonely</value>
|
||||
</field>
|
||||
</x>
|
||||
</query>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
extra_fields = [
|
||||
Field(
|
||||
"text-single",
|
||||
"urn:example:xmpp:free-text-search",
|
||||
"Where arth thou, my Juliet?",
|
||||
),
|
||||
Field(
|
||||
"text-single",
|
||||
"urn:example:xmpp:stanza-content",
|
||||
"{http://jabber.org/protocol/mood}mood/lonely",
|
||||
),
|
||||
]
|
||||
form = buildForm(extra_fields=extra_fields)
|
||||
d = self.plugin.queryArchive(self.client, MAMRequest(form), SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_query_prefs(self):
|
||||
xml = """
|
||||
<iq type='get' id='%s' to='%s'>
|
||||
<prefs xmlns='urn:xmpp:mam:1'>
|
||||
<always/>
|
||||
<never/>
|
||||
</prefs>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
d = self.plugin.get_prefs(self.client, SERVICE_JID)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
|
||||
def test_set_prefs(self):
|
||||
xml = """
|
||||
<iq type='set' id='%s' to='%s'>
|
||||
<prefs xmlns='urn:xmpp:mam:1' default='roster'>
|
||||
<always>
|
||||
<jid>romeo@montague.lit</jid>
|
||||
</always>
|
||||
<never>
|
||||
<jid>montague@montague.lit</jid>
|
||||
</never>
|
||||
</prefs>
|
||||
</iq>
|
||||
""" % (
|
||||
("H_%d" % domish.Element._idCounter),
|
||||
SERVICE,
|
||||
)
|
||||
always = [JID("romeo@montague.lit")]
|
||||
never = [JID("montague@montague.lit")]
|
||||
d = self.plugin.setPrefs(self.client, SERVICE_JID, always=always, never=never)
|
||||
d.addCallback(
|
||||
lambda __: self.assert_equal_xml(self.host.get_sent_message_xml(0), xml, True)
|
||||
)
|
||||
return d
|
||||
106
libervia/backend/test/test_plugin_xep_0334.py
Normal file
106
libervia/backend/test/test_plugin_xep_0334.py
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
|
||||
# SAT: a jabber client
|
||||
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
|
||||
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
|
||||
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# This program 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 Affero General Public License for more details.
|
||||
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
""" Plugin XEP-0334 """
|
||||
|
||||
from .constants import Const as C
|
||||
from libervia.backend.test import helpers
|
||||
from libervia.backend.plugins.plugin_xep_0334 import XEP_0334
|
||||
from twisted.internet import defer
|
||||
from wokkel.generic import parseXml
|
||||
from libervia.backend.core import exceptions
|
||||
|
||||
HINTS = ("no-permanent-storage", "no-storage", "no-copy")
|
||||
|
||||
|
||||
class XEP_0334Test(helpers.SatTestCase):
|
||||
def setUp(self):
|
||||
self.host = helpers.FakeSAT()
|
||||
self.plugin = XEP_0334(self.host)
|
||||
|
||||
def test_message_send_trigger(self):
|
||||
template_xml = """
|
||||
<message
|
||||
from='romeo@montague.net/orchard'
|
||||
to='juliet@capulet.com'
|
||||
type='chat'>
|
||||
<body>text</body>
|
||||
%s
|
||||
</message>
|
||||
"""
|
||||
original_xml = template_xml % ""
|
||||
|
||||
d_list = []
|
||||
|
||||
def cb(data, expected_xml):
|
||||
result_xml = data["xml"].toXml().encode("utf-8")
|
||||
self.assert_equal_xml(result_xml, expected_xml, True)
|
||||
|
||||
for key in HINTS + ("", "dummy_hint"):
|
||||
mess_data = {
|
||||
"xml": parseXml(original_xml.encode("utf-8")),
|
||||
"extra": {key: True},
|
||||
}
|
||||
treatments = defer.Deferred()
|
||||
self.plugin.messageSendTrigger(
|
||||
self.host.get_client(C.PROFILE[0]), mess_data, defer.Deferred(), treatments
|
||||
)
|
||||
if treatments.callbacks: # the trigger added a callback
|
||||
expected_xml = template_xml % ('<%s xmlns="urn:xmpp:hints"/>' % key)
|
||||
treatments.addCallback(cb, expected_xml)
|
||||
treatments.callback(mess_data)
|
||||
d_list.append(treatments)
|
||||
|
||||
return defer.DeferredList(d_list)
|
||||
|
||||
def test_message_received_trigger(self):
|
||||
template_xml = """
|
||||
<message
|
||||
from='romeo@montague.net/orchard'
|
||||
to='juliet@capulet.com'
|
||||
type='chat'>
|
||||
<body>text</body>
|
||||
%s
|
||||
</message>
|
||||
"""
|
||||
|
||||
def cb(__):
|
||||
raise Exception("Errback should not be ran instead of callback!")
|
||||
|
||||
def eb(failure):
|
||||
failure.trap(exceptions.SkipHistory)
|
||||
|
||||
d_list = []
|
||||
|
||||
for key in HINTS + ("dummy_hint",):
|
||||
message = parseXml(template_xml % ('<%s xmlns="urn:xmpp:hints"/>' % key))
|
||||
post_treat = defer.Deferred()
|
||||
self.plugin.message_received_trigger(
|
||||
self.host.get_client(C.PROFILE[0]), message, post_treat
|
||||
)
|
||||
if post_treat.callbacks:
|
||||
assert key in ("no-permanent-storage", "no-storage")
|
||||
post_treat.addCallbacks(cb, eb)
|
||||
post_treat.callback(None)
|
||||
d_list.append(post_treat)
|
||||
else:
|
||||
assert key not in ("no-permanent-storage", "no-storage")
|
||||
|
||||
return defer.DeferredList(d_list)
|
||||
Loading…
Reference in a new issue