All Downloads are FREE. Search and download functionalities are using the official Maven repository.

Lib.robot.htmldata.jsonwriter.py Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
#  Copyright 2008-2015 Nokia Solutions and Networks
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from robot.utils import PY2


class JsonWriter(object):

    def __init__(self, output, separator=''):
        self._writer = JsonDumper(output)
        self._separator = separator

    def write_json(self, prefix, data, postfix=';\n', mapping=None,
                   separator=True):
        self._writer.write(prefix)
        self._writer.dump(data, mapping)
        self._writer.write(postfix)
        self._write_separator(separator)

    def write(self, string, postfix=';\n', separator=True):
        self._writer.write(string + postfix)
        self._write_separator(separator)

    def _write_separator(self, separator):
        if separator and self._separator:
            self._writer.write(self._separator)


class JsonDumper(object):

    def __init__(self, output):
        self._output = output
        self._dumpers = (MappingDumper(self),
                         IntegerDumper(self),
                         TupleListDumper(self),
                         StringDumper(self),
                         NoneDumper(self),
                         DictDumper(self))

    def dump(self, data, mapping=None):
        for dumper in self._dumpers:
            if dumper.handles(data, mapping):
                dumper.dump(data, mapping)
                return
        raise ValueError('Dumping %s not supported.' % type(data))

    def write(self, data):
        self._output.write(data)


class _Dumper(object):
    _handled_types = None

    def __init__(self, jsondumper):
        self._dump = jsondumper.dump
        self._write = jsondumper.write

    def handles(self, data, mapping):
        return isinstance(data, self._handled_types)

    def dump(self, data, mapping):
        raise NotImplementedError


class StringDumper(_Dumper):
    _handled_types = (str, unicode) if PY2 else str
    _search_and_replace = [('\\', '\\\\'), ('"', '\\"'), ('\t', '\\t'),
                           ('\n', '\\n'), ('\r', '\\r'), ('




© 2015 - 2025 Weber Informatics LLC | Privacy Policy