示例#1
0
    def test_score_object(self):
        self.assertEqual(-1.0, ParserUtils.score_object(None))

        cls = make_dataclass("b", [("x", int), ("y", str), ("z", Any)])
        self.assertEqual(2.5, ParserUtils.score_object(cls(1, "1", None)))

        self.assertEqual(-1, ParserUtils.score_object(None))
        self.assertEqual(1.0, ParserUtils.score_object("a"))
        self.assertEqual(1.5, ParserUtils.score_object(2.9))
示例#2
0
    def bind(self, qname: str, text: NoneStr, tail: NoneStr,
             objects: List) -> bool:
        self.events.append(("end", qname, text, tail))

        if self.level > 0:
            self.level -= 1
            return False

        self.events.insert(
            0, ("start", qname, copy.deepcopy(self.attrs), self.ns_map))

        obj = None
        max_score = -1.0
        parent_namespace = target_uri(qname)
        for clazz in self.var.types:

            if is_dataclass(clazz):
                self.context.build(clazz, parent_ns=parent_namespace)
                candidate = self.parse_class(clazz)
            else:
                candidate = self.parse_value(text, [clazz])

            score = ParserUtils.score_object(candidate)
            if score > max_score:
                max_score = score
                obj = candidate

        if obj:
            objects.append((self.var.qname, obj))

            return True

        raise ParserError(f"Failed to parse union node: {self.var.qname}")
示例#3
0
文件: json.py 项目: igieon/xsdata
    def bind_dataclass_union(self, value: Dict, var: XmlVar) -> Any:
        """Bind data to all possible models and return the best candidate."""
        obj = None
        max_score = -1.0
        for clazz in var.types:
            candidate = self.bind_dataclass(value, clazz)
            score = ParserUtils.score_object(candidate)
            if score > max_score:
                max_score = score
                obj = candidate

        return obj
示例#4
0
    def bind(self, qname: str, text: NoneStr, tail: NoneStr, objects: List) -> bool:
        self.events.append(("end", qname, text, tail))

        if self.level > 0:
            self.level -= 1
            return False

        self.events.insert(0, ("start", qname, copy.deepcopy(self.attrs), self.ns_map))

        obj = None
        max_score = -1.0
        for clazz in self.var.types:
            candidate = self.parse_class(clazz)
            score = ParserUtils.score_object(candidate)
            if score > max_score:
                max_score = score
                obj = candidate

        if obj:
            objects.append((self.var.qname, obj))

            return True

        raise ParserError(f"Failed to parse union node: {self.var.qname}")