Exemple #1
0
    def test_client(self, mock_most):
        url = "http://localhost:9999/ws/hello"
        request = fixtures_dir.joinpath("hello/HelloRQ.xml").read_text()
        response = fixtures_dir.joinpath("hello/HelloRS.xml").read_bytes()
        headers = {"content-type": "text/xml"}
        mock_most.return_value = response

        config = Config.from_service(HelloGetHelloAsString)
        serializer = XmlSerializer(config=SerializerConfig(pretty_print=True))
        client = Client(config=config, serializer=serializer)
        result = client.send(
            {"body": {
                "get_hello_as_string": {
                    "arg0": "chris"
                }
            }})

        self.assertIsInstance(result, HelloGetHelloAsString.output)

        body = HelloGetHelloAsStringOutput.Body(
            get_hello_as_string_response=GetHelloAsStringResponse(
                return_value="Hello chris"))
        self.assertEqual(body, result.body)

        mock_most.assert_called_once_with(url, data=request, headers=headers)
Exemple #2
0
    def test_client_with_soap_fault(self, mock_most):
        url = "http://localhost:9999/ws/hello"
        request = fixtures_dir.joinpath("hello/HelloRQ.xml").read_text()
        response = fixtures_dir.joinpath(
            "hello/HelloRS_SoapFault.xml").read_bytes()
        headers = {"content-type": "text/xml"}
        mock_most.return_value = response

        config = Config.from_service(HelloGetHelloAsString)
        serializer = XmlSerializer(config=SerializerConfig(pretty_print=True))
        client = Client(config=config, serializer=serializer)
        result = client.send(
            {"body": {
                "get_hello_as_string": {
                    "arg0": "chris"
                }
            }})

        self.assertIsInstance(result, HelloGetHelloAsString.output)

        fault = HelloGetHelloAsStringOutput.Body.Fault(
            faultcode="S:Server",
            faultstring="foobar",
            detail=HelloGetHelloAsStringOutput.Body.Fault.Detail(
                hello_error=HelloError(message="foobar")),
        )
        self.assertEqual(fault, result.body.fault)

        mock_most.assert_called_once_with(url, data=request, headers=headers)
Exemple #3
0
def dumps(root_element, *, format=False) -> str:
    """Serialize a SDFormat object to an XML string.

    Parameters
    ----------
    root_element : object
        An instance of ``skbot.ignition.models.vXX.Sdf``. XX represents the SDFormat
        version and can be any version currently supported by scikit-bot.
    format : bool
        If true, add indentation and linebreaks to the output to increase human
        readability. If false (default) the entire XML will appear as a single
        line with no spaces between elements.

    Returns
    -------
    sdformat_string : str
        A string containing SDFormat XML representing the given input.

    Examples
    --------
    .. minigallery:: skbot.ignition.sdformat.dumps

    """
    serializer = XmlSerializer(config=SerializerConfig(pretty_print=format))

    return serializer.render(root_element)
Exemple #4
0
def validate_bindings(schema: Path, clazz: Type, output_format: str):
    __tracebackhide__ = True

    chapter = schema.stem.replace("chapter", "")

    sample = here.joinpath(f"samples/chapter{chapter}.xml")
    output_xml = here.joinpath(f"output/chapter{chapter}.xsdata.xml")
    output_json = here.joinpath(f"output/chapter{chapter}.xsdata.json")

    context = XmlContext(class_type=output_format)
    obj = XmlParser(context=context).from_path(sample, clazz)
    config = SerializerConfig(pretty_print=True)

    actual_json = JsonSerializer(context=context, config=config).render(obj)
    actual_xml = XmlSerializer(context=context, config=config).render(obj)

    if output_json.exists() and chapter != "13":
        assert output_json.read_text() == actual_json
        assert obj == JsonParser(context=context).from_string(
            actual_json, clazz)
    else:
        output_json.write_text(actual_json, encoding="utf-8")

    if output_xml.exists():
        assert output_xml.read_text() == actual_xml
    else:
        output_xml.write_text(actual_xml, encoding="utf-8")

    validator = etree.XMLSchema(etree.parse(str(schema)))
    validator.assertValid(etree.fromstring(actual_xml.encode()))
Exemple #5
0
    def __init__(self, *, config: Configuration) -> None:
        self.config = config

        self.serializer = XmlSerializer(config=SerializerConfig(
            pretty_print=False))
        self.parser = XmlParser(context=XmlContext())
        self.requests: WeakValueDictionary[str,
                                           Future] = WeakValueDictionary({})
        super().__init__()
Exemple #6
0
def serialize(obj: object, pretty_print: bool = False) -> str:
    ns_map = __get_ns_map(obj)
    schema_location = __get_ns_schema_location(obj)
    config = SerializerConfig(xml_version='1.0',
                              encoding='UTF-8',
                              schema_location=schema_location,
                              pretty_print=pretty_print)
    serializer = XmlSerializer(config=config)

    return serializer.render(obj, ns_map=ns_map)
Exemple #7
0
 def test_live(self):
     config = Config.from_service(HelloGetHelloAsString)
     serializer = XmlSerializer(config=SerializerConfig(pretty_print=True))
     client = Client(config=config, serializer=serializer)
     result = client.send(
         {"body": {
             "get_hello_as_string": {
                 "arg0": "chris"
             }
         }})
     print(result)
Exemple #8
0
    def setUp(self) -> None:
        super().setUp()

        output = StringIO()
        config = SerializerConfig()
        self.writer = XmlWriter(output=output, config=config)
        self.writer.handler = XMLGenerator(
            output,
            encoding="UTF-8",
            short_empty_elements=True,
        )
Exemple #9
0
 def write(cls, output: TextIO, obj: "GeneratorConfig"):
     ctx = XmlContext(
         element_name_generator=text.pascal_case,
         attribute_name_generator=text.camel_case,
     )
     config = SerializerConfig(pretty_print=True)
     serializer = XmlSerializer(context=ctx,
                                config=config,
                                writer=XmlEventWriter)
     serializer.write(output,
                      obj,
                      ns_map={None: "http://pypi.org/project/xsdata"})
Exemple #10
0
def writer(xrnsfile, song):

    xrns = XrnsSerializer()
    xml_song = xrns.render(song)

    config = SerializerConfig(pretty_print=True,
                              encoding="UTF-8",
                              xml_version="1.0")
    serializer = XmlSerializer(config=config)  # , writer=XmlEventWriter)

    rendered = serializer.render(xml_song)

    with zipfile.ZipFile(xrnsfile, mode="w") as zf:
        zf.writestr("Song.xml", rendered)
Exemple #11
0
    def test_client(self, mock_most):
        url = "http://www.dneonline.com/calculator.asmx"
        request = fixtures_dir.joinpath("calculator/AddRQ.xml").read_text()
        response = fixtures_dir.joinpath("calculator/AddRS.xml").read_bytes()
        headers = {"content-type": "text/xml", "SOAPAction": "http://tempuri.org/Add"}
        mock_most.return_value = response

        config = Config.from_service(CalculatorSoapAdd)
        serializer = XmlSerializer(config=SerializerConfig(pretty_print=True))
        client = Client(config=config, serializer=serializer)
        result = client.send({"Body": {"Add": {"intA": 1, "intB": 3}}})

        self.assertIsInstance(result, CalculatorSoapAddOutput)

        mock_most.assert_called_once_with(url, data=request, headers=headers)
Exemple #12
0
def write_file_from_xml(xml_file_path: pathlib.Path,
                        serialize_clazz: Optional[Type[T]]):
    """
    Method to write serialized XML data to a file.
    :param xml_file_path: A pathlib.path path object that the data will write to.
    :param serialize_clazz: A class Object.
    :return: N/A
    """
    serializer = XmlSerializer(
        config=SerializerConfig(pretty_print=True,
                                encoding="UTF-8",
                                xml_version="1.1",
                                xml_declaration=False,
                                schema_location="resources/xmltv.xsd",
                                no_namespace_schema_location=None))

    with xml_file_path.open("w") as data:
        serializer.write(data, serialize_clazz)
Exemple #13
0
    def __init_serializer(
        self, schema_location=None, no_namespace_schema_location=None
    ):
        """
        Inits the internal serializer.

        Parameters
        ----------
        schema_location: str
            Specify the xsi:schemaLocation attribute value
        no_namespace_schema_location: str
            Specify the xsi:noNamespaceSchemaLocation attribute value
        """
        config = SerializerConfig(
            pretty_print=True,
            schema_location=schema_location,
            no_namespace_schema_location=no_namespace_schema_location,
        )
        self.serializer = XmlSerializer(config=config)
Exemple #14
0
def validate_bindings(schema: Path, clazz: Type):
    __tracebackhide__ = True

    obj = XmlParser().from_path(schema.with_suffix(".xml"), clazz)
    actual = JsonSerializer(indent=4).render(obj)

    expected = schema.with_suffix(".json")
    if expected.exists():
        assert expected.read_text() == actual
        assert obj == JsonParser().from_string(actual, clazz)
    else:
        expected.write_text(actual, encoding="utf-8")

    config = SerializerConfig(pretty_print=True)
    xml = XmlSerializer(config=config).render(obj)

    validator = etree.XMLSchema(etree.parse(str(schema)))
    assert validator.validate(etree.fromstring(
        xml.encode())), validator.error_log

    expected.with_suffix(".xsdata.xml").write_text(xml, encoding="utf-8")
Exemple #15
0
from xsdata.models.enums import Mode
from xsdata.models.enums import Namespace
from xsdata.models.enums import ProcessType
from xsdata.models.enums import UseType
from xsdata.models.mixins import array_any_element
from xsdata.models.mixins import array_element
from xsdata.models.mixins import attribute
from xsdata.models.mixins import element
from xsdata.models.mixins import ElementBase
from xsdata.models.mixins import ModuleMixin
from xsdata.utils import text
from xsdata.utils.collections import unique_sequence
from xsdata.utils.namespaces import clean_uri

docstring_serializer = XmlSerializer(
    config=SerializerConfig(pretty_print=True, xml_declaration=False)
)

DEFAULT_ATTR_NAME = "@value"


@dataclass(frozen=True)
class Docstring:
    class Meta:
        namespace = "http://www.w3.org/1999/xhtml"

    elements: Array[object] = array_any_element()


@dataclass
class Documentation(ElementBase):
Exemple #16
0
 def setUp(self):
     config = SerializerConfig(pretty_print=True)
     self.serializer = XmlSerializer(config=config, writer=LxmlEventWriter)
Exemple #17
0
 def to_xml(cls: Type[ME], obj: T) -> str:
     context = XmlContext(element_name_generator=str.upper)
     config = SerializerConfig(pretty_print=True)
     serializer = XmlSerializer(context=context, config=config)
     return serializer.render(obj)
Exemple #18
0
import sys
from pathlib import Path

from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig

from reqif.models import ReqIf

here = Path(__file__).parent

xml_fixture = here.joinpath("sample.xml")
parser = XmlParser()
config = SerializerConfig(pretty_print=True, encoding="ascii")
serializer = XmlSerializer(context=parser.context, config=config)

obj = parser.from_path(xml_fixture, ReqIf)
ns_map = {
    None: "http://www.omg.org/spec/ReqIF/20110401/reqif.xsd",
    "xhtml": "http://www.w3.org/1999/xhtml",
}
serializer.write(sys.stdout, obj, ns_map=ns_map)
Exemple #19
0
from xsdata.cli import cli
from xsdata.formats.dataclass.context import XmlContext
from xsdata.formats.dataclass.parsers import JsonParser
from xsdata.formats.dataclass.parsers import XmlParser
from xsdata.formats.dataclass.serializers import JsonSerializer
from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.serializers.config import SerializerConfig
from xsdata.utils import text
from xsdata.utils.testing import load_class

log = logging.getLogger()

w3c = Path(__file__).absolute().parent.parent.joinpath("w3c")
output = Path(__file__).absolute().parent.parent.joinpath("output/instances")
os.chdir(w3c.parent)
config = SerializerConfig(pretty_print=True)


def assert_bindings(
    schema: str,
    instance: str,
    class_name: str,
    version: str,
    mode: str,
    save_output: bool,
    output_format: str,
    structure_style: str,
):
    __tracebackhide__ = True

    if mode == "xml":
Exemple #20
0
def ToXML(header: ismrmrdHeader, encoding='ascii'):
    config = SerializerConfig(encoding=encoding, pretty_print=True)
    serializer = XmlSerializer(config)
    return serializer.render(header)
Exemple #21
0
from xsdata.models.enums import FormType
from xsdata.models.enums import Mode
from xsdata.models.enums import Namespace
from xsdata.models.enums import ProcessType
from xsdata.models.enums import UseType
from xsdata.models.mixins import array_any_element
from xsdata.models.mixins import array_element
from xsdata.models.mixins import attribute
from xsdata.models.mixins import element
from xsdata.models.mixins import ElementBase
from xsdata.models.mixins import ModuleMixin
from xsdata.utils import text
from xsdata.utils.collections import unique_sequence
from xsdata.utils.namespaces import clean_uri

docstring_serializer = XmlSerializer(config=SerializerConfig(
    pretty_print=True))


@dataclass(frozen=True)
class Docstring:
    elements: Array[object] = array_any_element()


@dataclass
class Documentation(ElementBase):
    """
    Model representation of a schema xs:documentation element.

    :param lang: language
    :param source: anyURI
    :param elements: ({any})*
Exemple #22
0
def serializer_config():
    return SerializerConfig(pretty_print=True, ignore_default_attributes=True)