diff libervia/backend/test/helpers.py @ 4270:0d7bb4df2343

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents bc7d45dedeb0
children
line wrap: on
line diff
--- a/libervia/backend/test/helpers.py	Tue Jun 18 12:06:45 2024 +0200
+++ b/libervia/backend/test/helpers.py	Wed Jun 19 18:44:57 2024 +0200
@@ -20,10 +20,12 @@
 
 ## logging configuration for tests ##
 from libervia.backend.core import log_config
+
 log_config.libervia_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
@@ -49,7 +51,7 @@
     @return: unicode conversion, according to bridge convention
 
     """
-    return  "True" if value else "False"
+    return "True" if value else "False"
 
 
 def mute_logging():
@@ -98,13 +100,15 @@
         self.profiles = {}
 
     def contact_del(self, to, profile_key):
-        #TODO
+        # 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@'):
+    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):
@@ -113,7 +117,7 @@
         @param mess_data: message data dictionnary
         @param client: profile's client
         """
-        client.xmlstream.send(mess_data['xml'])
+        client.xmlstream.send(mess_data["xml"])
         return mess_data
 
     def _store_message(self, mess_data, client):
@@ -190,7 +194,9 @@
         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):
+    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
@@ -211,7 +217,7 @@
         To be called from your tests when needed.
         """
         client = self.get_client(profile_key)
-        if not hasattr(client, 'features'):
+        if not hasattr(client, "features"):
             client.features = {}
         if jid_ not in client.features:
             client.features[jid_] = set()
@@ -248,7 +254,9 @@
 
         setattr(self, name, check_call)
 
-    def add_method(self, name, int_suffix, in_sign, out_sign, method, async_=False, doc=None):
+    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):
@@ -271,19 +279,19 @@
         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@'):
+    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@'):
+    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@':
+        if profile_key == "@DEFAULT@":
             return C.PROFILE[0]
-        elif profile_key == '@NONE@':
+        elif profile_key == "@NONE@":
             raise exceptions.ProfileNotSetError
         else:
             return profile_key
@@ -315,13 +323,24 @@
     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@"):
+    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@'):
+    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@'):
+    def set_presence_status(
+        self, contact_jid, show, priority, statuses, profile_key="@DEFAULT@"
+    ):
         pass
 
     def add_waiting_sub(self, type_, contact_jid, profile_key):
@@ -330,7 +349,9 @@
     def del_waiting_sub(self, contact_jid, profile_key):
         pass
 
-    def update_entity_data(self, entity_jid, key, value, silent=False, profile_key="@NONE@"):
+    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
 
@@ -366,10 +387,16 @@
             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)}
+        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)
+            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)
 
@@ -386,13 +413,13 @@
         @param obj (domish.Element, str or unicode): message to send
         """
         if not isinstance(obj, domish.Element):
-            assert(isinstance(obj, str) or isinstance(obj, str))
+            assert isinstance(obj, str) or isinstance(obj, str)
             obj = parseXml(obj)
 
-        if obj.name == 'iq':
+        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.iqDeferreds[obj["id"]].callback(obj)
 
         self.sent.append(obj)
         return defer.succeed(None)
@@ -424,27 +451,27 @@
         def equal_elt(got_elt, exp_elt):
             if ignore_blank:
                 for elt in got_elt, exp_elt:
-                    for attr in ('text', 'tail'):
+                    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):
+            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):
+            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):
+            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)):
+            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
@@ -454,17 +481,24 @@
             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])
+            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)
+        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("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