def test_iterable(self):
        """
        Tests dump & load of iterable types
        """
        tuple_values = (42, 42.12, "string", True, False, None)
        list_values = list(tuple_values)
        set_values = set(tuple_values)
        frozen_values = frozenset(tuple_values)

        for iterable in (tuple_values, list_values, set_values, frozen_values):
            # Dump...
            serialized = dump(iterable)
            # Reload...
            deserialized = load(serialized)

            self.assertIs(
                type(serialized), list, "Dumped iterable should be a list"
            )
            self.assertIs(
                type(deserialized), list, "Loaded iterable should be a list"
            )

            # Check content
            self.assertCountEqual(
                deserialized, tuple_values, "Values order changed"
            )
    def test_primitive(self):
        """
        Tests dump & load of primitive types
        """
        for value in (42, 42.12, "string", True, False, None):
            # Dump..
            serialized = dump(value)
            # Reload...
            deserialized = load(serialized)

            self.assertIs(
                type(serialized),
                type(value),
                "Type changed during serialization",
            )
            self.assertIs(
                type(deserialized),
                type(value),
                "Type changed during deserialization",
            )

            self.assertEqual(
                serialized, value, "Value changed during serialization"
            )
            self.assertEqual(
                deserialized, value, "Value changed during deserialization"
            )
    def test_object(self):
        """
        Tests dump & load of a custom type
        """
        types = {
            Bean: ("public", "_protected", "_Bean__private"),
            InheritanceBean: ("public", "_protected", "first", "_second"),
            SlotBean: ("public", "_protected"),
            InheritanceSlotBean: ("public", "_protected", "first", "_second"),
            SecondInheritanceSlotBean: (
                "public",
                "_protected",
                "first",
                "_second",
                "third",
                "_fourth",
            ),
        }

        for clazz, fields in types.items():
            # Prepare the bean
            data = clazz()

            # Dump it...
            serialized = dump(data)

            # Check serialized content
            self.assertIn("__jsonclass__", serialized)
            for field in fields:
                self.assertIn(field, serialized)

            # Check class name
            self.assertEqual(
                serialized["__jsonclass__"][0],
                "{0}.{1}".format(clazz.__module__, clazz.__name__),
            )

            # Reload it
            deserialized = load(serialized)

            # Dictionary is left as-is
            self.assertIn(
                "__jsonclass__",
                serialized,
                "Serialized dictionary has been modified",
            )
            self.assertFalse(
                hasattr(deserialized, "__jsonclass__"),
                "The deserialized bean shouldn't have a "
                "__jsonclass__ attribute",
            )

            # Check deserialized value
            self.assertIs(type(deserialized), type(data))
            self.assertEqual(
                deserialized, data, "Source and deserialized bean are not equal"
            )
    def test_enum(self):
        """
        Tests the serialization of enumerations
        """
        if enum is None:
            self.skipTest("enum package not available.")

        for data in (Color.BLUE, Color.RED):
            # Serialization
            enum_serialized = dump(data)
            self.assertIn(Color.__name__, enum_serialized["__jsonclass__"][0])
            self.assertEqual(data.value, enum_serialized["__jsonclass__"][1][0])

            # Loading
            result = load(enum_serialized)
            self.assertEqual(data, result)

        # Embedded
        data = [Color.BLUE, Color.RED]
        serialized = dump(data)
        result = load(serialized)
        self.assertListEqual(data, result)
Exemple #5
0
    def test_enum(self):
        """
        Tests the serialization of enumerations
        """
        if enum is None:
            self.skipTest("enum package not available.")

        for data in (Color.BLUE, Color.RED):
            # Serialization
            enum_serialized = dump(data)
            self.assertIn(
                Color.__name__, enum_serialized['__jsonclass__'][0])
            self.assertEqual(
                data.value, enum_serialized['__jsonclass__'][1][0])

            # Loading
            result = load(enum_serialized)
            self.assertEqual(data, result)

        # Embedded
        data = [Color.BLUE, Color.RED]
        serialized = dump(data)
        result = load(serialized)
        self.assertListEqual(data, result)
Exemple #6
0
def loads(data):
    """
    This differs from the Python implementation, in that it returns
    the request structure in Dict format instead of the method, params.
    It will return a list in the case of a batch request / response.
    """
    if data == '':
        # notification
        return None
    result = jloads(data)
    # if the above raises an error, the implementing server code
    # should return something like the following:
    # { 'jsonrpc':'2.0', 'error': fault.error(), id: None }
    if config.use_jsonclass is True:
        from jsonrpclib import jsonclass
        result = jsonclass.load(result)
    return result
    def test_dictionary(self):
        """
        Tests dump & load of dictionaries
        """
        dictionary = {'int': 42,
                      'float': 42.2,
                      None: "string",
                      True: False,
                      42.1: None,
                      'dict': {"sub": 1},
                      "list": [1, 2, 3]}

        # Dump it
        serialized = dump(dictionary)
        # Reload it
        deserialized = load(serialized)

        self.assertDictEqual(deserialized, dictionary)
    def test_object(self):
        """
        Tests dump & load of a custom type
        """
        types = {Bean: ('public', '_protected', '_Bean__private'),
                 InheritanceBean: ('public', '_protected', 'first', '_second'),
                 SlotBean: ('public', '_protected'),
                 InheritanceSlotBean: ('public', '_protected',
                                       'first', '_second'),
                 SecondInheritanceSlotBean: ('public', '_protected',
                                             'first', '_second',
                                             'third', '_fourth'), }

        for clazz, fields in types.items():
            # Prepare the bean
            data = clazz()

            # Dump it...
            serialized = dump(data)

            # Check serialized content
            self.assertIn('__jsonclass__', serialized)
            for field in fields:
                self.assertIn(field, serialized)

            # Check class name
            self.assertEqual(serialized['__jsonclass__'][0],
                             '{0}.{1}'.format(clazz.__module__,
                                              clazz.__name__))

            # Reload it
            deserialized = load(serialized)

            # Dictionary is left as-is
            self.assertIn('__jsonclass__', serialized,
                          "Serialized dictionary has been modified")
            self.assertFalse(hasattr(deserialized, '__jsonclass__'),
                             "The deserialized bean shouldn't have a "
                             "__jsonclass__ attribute")

            # Check deserialized value
            self.assertIs(type(deserialized), type(data))
            self.assertEqual(deserialized, data,
                             "Source and deserialized bean are not equal")
    def test_primitive(self):
        """
        Tests dump & load of primitive types
        """
        for value in (42, 42.12, "string", True, False, None):
            # Dump..
            serialized = dump(value)
            # Reload...
            deserialized = load(serialized)

            self.assertIs(type(serialized), type(value),
                          "Type changed during serialization")
            self.assertIs(type(deserialized), type(value),
                          "Type changed during deserialization")

            self.assertEqual(serialized, value,
                             "Value changed during serialization")
            self.assertEqual(deserialized, value,
                             "Value changed during deserialization")
Exemple #10
0
def load(data):
    """
    Loads a JSON-RPC request/response dictionary. Calls jsonclass to load beans
    
    :param data: A JSON-RPC dictionary
    :return: A parsed dictionary or None
    """
    if data is None:
        # Notification
        return None

    # if the above raises an error, the implementing server code
    # should return something like the following:
    # { 'jsonrpc':'2.0', 'error': fault.error(), id: None }
    if config.use_jsonclass:
        # Convert beans
        data = jsonclass.load(data)

    return data
Exemple #11
0
def load(data, config=jsonrpclib.config.DEFAULT):
    """
    Loads a JSON-RPC request/response dictionary. Calls jsonclass to load beans

    :param data: A JSON-RPC dictionary
    :param config: A JSONRPClib Config instance (or None for default values)
    :return: A parsed dictionary or None
    """
    if data is None:
        # Notification
        return None

    # if the above raises an error, the implementing server code
    # should return something like the following:
    # { 'jsonrpc':'2.0', 'error': fault.error(), id: None }
    if config.use_jsonclass:
        # Convert beans
        data = jsonclass.load(data, config.classes)

    return data
Exemple #12
0
    def test_dictionary(self):
        """
        Tests dump & load of dictionaries
        """
        dictionary = {
            "int": 42,
            "float": 42.2,
            None: "string",
            True: False,
            42.1: None,
            "dict": {"sub": 1},
            "list": [1, 2, 3],
        }

        # Dump it
        serialized = dump(dictionary)
        # Reload it
        deserialized = load(serialized)

        self.assertDictEqual(deserialized, dictionary)
    def test_iterable(self):
        """
        Tests dump & load of iterable types
        """
        tuple_values = (42, 42.12, "string", True, False, None)
        list_values = list(tuple_values)
        set_values = set(tuple_values)
        frozen_values = frozenset(tuple_values)

        for iterable in (tuple_values, list_values, set_values, frozen_values):
            # Dump...
            serialized = dump(iterable)
            # Reload...
            deserialized = load(serialized)

            self.assertIs(type(serialized), list,
                          "Dumped iterable should be a list")
            self.assertIs(type(deserialized), list,
                          "Loaded iterable should be a list")

            # Check content
            self.assertCountEqual(deserialized, tuple_values,
                                  "Values order changed")