Exemplo n.º 1
0
    def check_select(self, path, expected, context=None):
        """
        Checks the materialized result of the *select* method with an XPath expression.
        The selection is applied on the root token of the parsed XPath expression.

        :param path: an XPath expression.
        :param expected: the expected result. Can be a data instance to compare to the result, \
        a function that accepts the result as argument and returns a boolean value, an exception \
        class that is raised by running the evaluate method.
        :param context: an optional `XPathContext` instance to be passed to evaluate method. If no \
        context is provided the method is called with a dummy context.
        """
        if context is None:
            context = XPathContext(root=self.etree.Element(u'dummy_root'))
        else:
            context = context.copy()
        root_token = self.parser.parse(path)
        if isinstance(expected, type) and issubclass(expected, Exception):
            self.assertRaises(expected, root_token.select, context)
        elif isinstance(expected, list):
            self.assertListEqual(list(root_token.select(context)), expected)
        elif isinstance(expected, set):
            self.assertEqual(set(root_token.select(context)), expected)
        elif not callable(expected):
            self.assertEqual(list(root_token.select(context)), expected)
        else:
            self.assertTrue(
                expected(list(root_token.parse(path).select(context))))
Exemplo n.º 2
0
    def __call__(self,
                 elem,
                 value=None,
                 source=None,
                 namespaces=None,
                 **kwargs):
        if value is not None:
            self.parser.variables['value'] = self.base_type.text_decode(value)
        if not self.parser.is_schema_bound():
            self.parser.schema.bind_parser(self.parser)

        if source is None:
            context = XPathContext(root=elem)
        else:
            context = XPathContext(root=source.root, item=elem)

        default_namespace = self.parser.namespaces['']
        if namespaces and '' in namespaces:
            self.parser.namespaces[''] = namespaces['']

        try:
            if not self.token.evaluate(context.copy()):
                msg = "expression is not true with test path %r."
                yield XMLSchemaValidationError(self,
                                               obj=elem,
                                               reason=msg % self.path)
        except ElementPathError as err:
            yield XMLSchemaValidationError(self, obj=elem, reason=str(err))

        self.parser.namespaces[''] = default_namespace