コード例 #1
0
    def func_serialize(self, args):
        r"""Default method for serializing object into message.

        Args:
            args (obj): List of arguments to be formatted or a ready made message.

        Returns:
            bytes, str: Serialized message.

        Raises:
            Exception: If there is no format string and more than one argument
                is provided.

        """
        if self._func_serialize is not None:
            # Return directly to check and raise TypeError
            return self._func_serialize(args)
        elif self.format_str is not None:
            if self.as_array:
                out = serialize.array_to_bytes(args,
                                               dtype=self.numpy_dtype,
                                               order='F')
            else:
                out = serialize.format_message(args, self.format_str)
        else:
            if isinstance(args, (list, tuple)):
                if len(args) != 1:
                    raise Exception("No format string and more than one " +
                                    "argument provided.")
                out = args[0]
            else:
                out = args
        out = backwards.unicode2bytes(out)
        return out
コード例 #2
0
    def format_line(self, *args):
        r"""Create a line from the provided arguments using the table format.

        Args:
            \*args: Arguments to create line from.

        Returns:
            str: The line created from the arguments.

        """
        return serialize.format_message(args, self.format_str)
コード例 #3
0
def test_format_message():
    r"""Test formatting message from a list or arguments and back."""
    fmt = backwards.unicode2bytes("%5s\t%ld\t%lf\t%g%+gj\n")
    dtype = serialize.cformat2nptype(fmt)
    x_arr = np.ones(1, dtype)
    x_tup = [x_arr[n][0] for n in x_arr.dtype.names]
    # x_tup[0] = backwards.bytes2unicode(x_tup[0])
    flist = [fmt, "%ld"]
    alist = [tuple(x_tup), 0]
    for a, f in zip(alist, flist):
        msg = serialize.format_message(a, f)
        b = serialize.process_message(msg, f)
        if not isinstance(a, tuple):
            nt.assert_equal(b, (a, ))
        else:
            nt.assert_equal(b, a)
    # Errors
    nt.assert_raises(RuntimeError, serialize.format_message, (0, ), "%d %d")
    nt.assert_raises(TypeError, serialize.process_message, 0, "%d")
    nt.assert_raises(ValueError, serialize.process_message,
                     backwards.unicode2bytes("hello"), "%d")