Exemple #1
0
    def assertXmlEqual(self, got, want):
        """ fail if the two objects are not equal XML serializations
        In case of a failure, both serializations are pretty printed
        with differences marked.
        There is not check well-formedness or against any schema, only
        slightly intelligent matching of the tested string to the reference
        string.

        '...' can be used as a wildcard instead of nodes or attribute values.

        Wildcard Examples:
            <foo>...</foo>
            <foo bar="..." />

        Arguments:
            got -- string to check, as unicode string
            want -- reference string, as unicode string

        Usage Example:
            self.assertXmlEqual(etree.tounicode(...), reference)
        """
        checker = LXMLOutputChecker()
        if not checker.check_output(want, got, 0):
            message = checker.output_difference(Example("", want), got, 0)
            raise AssertionError(message)
Exemple #2
0
 def assertXmlEqual(self, want, got):
     checker = LXMLOutputChecker()
     if not checker.check_output(want, got, 0):
         message = checker.output_difference(Example("", want), got, 0)
         for line in difflib.unified_diff(want.splitlines(1), got.splitlines(1), fromfile='want.xml', tofile='got.xml'):
             print line
         raise AssertionError(message)
Exemple #3
0
def assertXmlEqual(result, expect):
    from doctest import Example
    from lxml.doctestcompare import LXMLOutputChecker
    checker = LXMLOutputChecker()
    if not checker.check_output(expect, result, 0):
        message = checker.output_difference(Example("", expect), result, 0)
        raise AssertionError(message)
Exemple #4
0
def assert_xml_equal(got, want):
    got = lxml.html.tostring(got)
    want = lxml.html.tostring(want)
    checker = LXMLOutputChecker()
    if not checker.check_output(want, got, 0):
        message = checker.output_difference(Example("", want), got, 0)
        raise AssertionError(message)
Exemple #5
0
    def assertXmlEqual(self, got, want):
        """ fail if the two objects are not equal XML serializations
        In case of a failure, both serializations are pretty printed
        with differences marked.
        There is not check well-formedness or against any schema, only
        slightly intelligent matching of the tested string to the reference
        string.

        '...' can be used as a wildcard instead of nodes or attribute values.

        Wildcard Examples:
            <foo>...</foo>
            <foo bar="..." />

        Arguments:
            got -- string to check, as unicode string
            want -- reference string, as unicode string

        Usage Example:
            self.assertXmlEqual(etree.tounicode(...), reference)
        """
        checker = LXMLOutputChecker()
        if not checker.check_output(want, got, 0):
            message = checker.output_difference(Example("", want), got, 0)
            raise AssertionError(message)
Exemple #6
0
def assert_xml_equal(got, want):
    assert want is not None, 'Wanted XML cannot be None'
    if got is None:
        raise AssertionError('Got input to validate was None')
    checker = LXMLOutputChecker()
    if not checker.check_output(want, got, 0):
        message = checker.output_difference(Example("", want), got, 0)
        raise AssertionError(message)
Exemple #7
0
def assert_xml_equal(expected_xml, got_xml, context_explanation=""):
    checker = LXMLOutputChecker()
    if not checker.check_output(expected_xml, got_xml, 0):
        raise AssertionError("{context_explanation}{xml_diff}".format(
            context_explanation=("" if not context_explanation else
                                 "\n{0}\n".format(context_explanation)),
            xml_diff=checker.output_difference(
                doctest.Example("", expected_xml), got_xml, 0)))
Exemple #8
0
def assert_xml_equal(expected_xml, got_xml):
    checker = LXMLOutputChecker()
    if not checker.check_output(expected_xml, got_xml, 0):
        raise AssertionError(checker.output_difference(
            doctest.Example("", expected_xml),
            got_xml,
            0
        ))
Exemple #9
0
 def assertXmlEqual(self, want, got):
     # snippet from http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342
     checker = LXMLOutputChecker()
     if not checker.check_output(want, got, 0):
         message = "XML mismatch\n\n"
         for line in difflib.unified_diff(want.splitlines(1), got.splitlines(1), fromfile='want.xml', tofile='got.xml'):
             message += line + '\n'
         raise AssertionError(message)
Exemple #10
0
def assert_xml_equal(got, want):
    assert want is not None, 'Wanted XML cannot be None'
    if got is None:
        raise AssertionError('Got input to validate was None')
    checker = LXMLOutputChecker()
    if not checker.check_output(want, got, 0):
        message = checker.output_difference(Example("", want), got, 0)
        raise AssertionError(message)
Exemple #11
0
    def assertXmlEqual(self, got, want):
        from lxml.doctestcompare import LXMLOutputChecker
        from doctest import Example

        checker = LXMLOutputChecker()
        if checker.check_output(want, got, 0):
            return
        message = checker.output_difference(Example("", want), got, 0)
        raise AssertionError(message)
Exemple #12
0
def assertXmlEqual(got, want):
    from lxml.doctestcompare import LXMLOutputChecker
    from doctest import Example

    checker = LXMLOutputChecker()
    if checker.check_output(want, got, 0):
        return
    message = checker.output_difference(Example("", want), got, 0)
    raise AssertionError(message)
Exemple #13
0
 def assertXmlEqual(self, got, want):
     if isinstance(got, (et._Element, et._ElementTree)):
         got = et.tostring(got).decode()
     if isinstance(want, (et._Element, et._ElementTree)):
         want = et.tostring(want).decode()
     checker = LXMLOutputChecker()
     if not checker.check_output(want, got, 0):
         message = checker.output_difference(Example("", want), got, 0)
         raise AssertionError(message)
Exemple #14
0
    def assertXmlFilesEqual(self, result_filename, expected_filename):
        with open(result_filename) as rf:
            got = rf.read()
        with open(expected_filename) as ef:
            want = ef.read()

        checker = LXMLOutputChecker()
        if not checker.check_output(want, got, 0):
            message = checker.output_difference(Example("", got), want, 0)
            raise AssertionError(message)
    def assertXmlEquivalent(self, got, expect):
        """Asserts both xml parse to the same results
        `got` may be an XML string or lxml Element
        """
        checker = LXMLOutputChecker()

        if isinstance(got, etree._Element):
            got = etree.tostring(got)

        if not checker.check_output(expect, got, PARSE_XML):
            message = checker.output_difference(doctest.Example("", expect), got, PARSE_XML)
            self.fail(message)
Exemple #16
0
def assert_xml_equal(got: Union[bytes, str], want: str):
    """Compare two XML strings."""
    checker = LXMLOutputChecker()
    if isinstance(got, str) and got.startswith("<?"):
        # Strip <?xml version='1.0' encoding="UTF-8" ?>
        got = got[got.index("?>") + 3 :]

    if not checker.check_output(want, got, PARSE_XML):
        example = Example("", "")
        example.want = want  # unencoded, avoid doctest for bytes type.
        message = checker.output_difference(example, got, PARSE_XML)
        raise AssertionError(message)
    def assertXmlEquivalent(self, got, expect):
        """Asserts both xml parse to the same results
        `got` may be an XML string or lxml Element
        """
        checker = LXMLOutputChecker()

        if isinstance(got, etree._Element):
            got = etree.tostring(got)

        if not checker.check_output(expect, got, PARSE_XML):
            message = checker.output_difference(doctest.Example("", expect),
                                                got, PARSE_XML)
            self.fail(message)
Exemple #18
0
def assertEqualXML(test, expected):
    output_checker = LXMLOutputChecker()
    if not output_checker.check_output(expected, test, PARSE_XML):
        diff = output_checker.output_difference(Example("", expected), test, PARSE_XML)
        msg = diff
        for line in diff.split("\n"):
            if msg == diff:
                msg = msg + "\nDiff summary:\n"
            if "got:" in line or line.strip().startswith(('+', '-')):
                msg = msg + line + "\n"
        if msg == "":
            msg = diff
        raise AssertionError(msg)
Exemple #19
0
def compare_xml(generated, expected):
    """Use doctest checking from lxml for comparing XML trees. Returns diff if the two are not the same"""
    checker = LXMLOutputChecker()

    class DummyDocTest():
        pass

    ob = DummyDocTest()
    ob.want = expected

    check = checker.check_output(expected, generated, PARSE_XML)
    if check is False:
        diff = checker.output_difference(ob, generated, PARSE_XML)
        return diff
Exemple #20
0
def assertEqualXML(test, expected):
    output_checker = LXMLOutputChecker()
    if not output_checker.check_output(expected, test, PARSE_XML):
        diff = output_checker.output_difference(Example("", expected), test,
                                                PARSE_XML)
        msg = diff
        for line in diff.split("\n"):
            if msg == diff:
                msg = msg + "\nDiff summary:\n"
            if "got:" in line or line.strip().startswith(('+', '-')):
                msg = msg + line + "\n"
        if msg == "":
            msg = diff
        raise AssertionError(msg)
    def assertXmlEquivalentOutputs(self, data, expected):
        """Asserts both XML outputs are equivalent.

        This assertion use the powerful but dangerous feature of
        LXMLOutputChecker. Powerful because one can compare two XML document
        in their meaning, but dangerous because sometimes there is more to
        check than just a kind of output.

        See LXMLOutputChecker documentation for more information.
        """
        checker = LXMLOutputChecker()

        if not checker.check_output(expected, data, PARSE_XML):
            self.fail("Output are not equivalent:\n" "Given: %s\n" "Expected: %s" % (data, expected))
Exemple #22
0
def compare_xml(generated, expected):
    """Use doctest checking from lxml for comparing XML trees. Returns diff if the two are not the same"""
    checker = LXMLOutputChecker()

    class DummyDocTest():
        pass

    ob = DummyDocTest()
    ob.want = generated

    check = checker.check_output(expected, generated, PARSE_XML)
    if check is False:
        diff = checker.output_difference(ob, expected, PARSE_XML)
        return diff
Exemple #23
0
def assert_xml_equal(expected_xml, got_xml, context_explanation=""):
    checker = LXMLOutputChecker()
    if not checker.check_output(expected_xml, got_xml, 0):
        raise AssertionError(
            "{context_explanation}{xml_diff}".format(
                context_explanation=(
                    "" if not context_explanation
                    else "\n{0}\n".format(context_explanation)
                ),
                xml_diff=checker.output_difference(
                    doctest.Example("", expected_xml),
                    got_xml,
                    0
                )
            )
        )
    def assertXmlEquivalentOutputs(self, data, expected):
        """Asserts both XML outputs are equivalent.

        This assertion use the powerful but dangerous feature of
        LXMLOutputChecker. Powerful because one can compare two XML document
        in their meaning, but dangerous because sometimes there is more to
        check than just a kind of output.

        See LXMLOutputChecker documentation for more information.

        """
        checker = LXMLOutputChecker()

        if not checker.check_output(expected, data, PARSE_XML):
            self.fail('Output are not equivalent:\n'
                      'Given: %s\n'
                      'Expected: %s' % (data, expected))
Exemple #25
0
    def assertXmlEqual(self, expected, actual, normalize=True):
        if normalize:
            expected = parse_normalize(expected)
            actual = parse_normalize(actual)

        # snippet from http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342
        checker = LXMLOutputChecker()
        if not checker.check_output(expected, actual, 0):
            message = "XML mismatch\n\n"
            diff = difflib.unified_diff(
                expected.splitlines(1),
                actual.splitlines(1),
                fromfile='want.xml',
                tofile='got.xml'
            )
            for line in diff:
                message += line
            raise AssertionError(message)
Exemple #26
0
    def assertXmlEqual(self, expected, actual, normalize=True):
        if normalize:
            parser = lxml.etree.XMLParser(remove_blank_text=True)
            parse = lambda *args: normalize_attributes(lxml.etree.XML(*args))
            expected = lxml.etree.tostring(parse(expected, parser), pretty_print=True)
            actual = lxml.etree.tostring(parse(actual, parser), pretty_print=True)

        # snippet from http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342
        checker = LXMLOutputChecker()
        if not checker.check_output(expected, actual, 0):
            message = "XML mismatch\n\n"
            diff = difflib.unified_diff(
                expected.splitlines(1),
                actual.splitlines(1),
                fromfile='want.xml',
                tofile='got.xml'
            )
            for line in diff:
                message += line
            raise AssertionError(message)
	def assertXmlEqual(self, want, got):
		checker = LXMLOutputChecker()
		if not checker.check_output(want, got, 0):
			message = checker.output_difference(Example("", want), got, 0)
			raise AssertionError(message)
Exemple #28
0
def compare_xml(expected, given, diff_format=PARSE_XML):
    checker = LXMLOutputChecker()
    if not checker.check_output(expected.strip(), given.strip(), PARSE_XML):
        raise AssertionError(checker.output_difference(Example('', expected), given.decode('utf8'), diff_format))
Exemple #29
0
 def assertXmlEqual(self, want, got):
     checker = LXMLOutputChecker()
     if not checker.check_output(want, got, 0):
         message = checker.output_difference(Example("", want), got, 0)
         raise AssertionError(message)
Exemple #30
0
class TestXform(unittest.TestCase):
    def setUp(self):
        self.checker = LXMLOutputChecker()

    def test_should_return_list_of_required_forms(self):
        form_tuples = [("name", "id", False), ("name2", "id2", False)]
        base_url = "baseURL"
        self.assertEqual(list_all_forms(form_tuples, base_url),
                         unicode(expected_response_for_get_all_forms))

    def mock_constraint(self):
        mock_constraint = Mock()
        mock_constraint.xform_constraint.return_value = 'constraint'
        return mock_constraint

    def test_should_return_specific_form_for_project_without_unique_id(self):
        dbm = Mock()
        questionnaire_mock = Mock()
        field1 = Field(type='text',
                       name='name',
                       label='name',
                       code='code',
                       instruction='instruction',
                       constraints=[(self.mock_constraint())])
        questionnaire_mock.name = 'name'
        questionnaire_mock.fields = [field1]
        questionnaire_mock.form_code = 'form_code'
        questionnaire_mock.id = 'id'
        questionnaire_mock.unique_id_field = None
        questionnaire_mock.activeLanguages = ["en"]
        questionnaire_mock.xform = None
        with patch("mangrove.transport.xforms.xform.FormModel"
                   ) as form_model_mock:
            form_model_mock.get.return_value = questionnaire_mock
            actual_response = xform_for(dbm, "someFormId", 'rep1')
            self.assertTrue(
                self.checker.check_output(
                    actual_response,
                    unicode(expected_xform_for_project_on_reporter), 0),
                actual_response)

    def text_field(self, code):
        return Field(type='text',
                     name='name',
                     label='name',
                     code=code,
                     instruction='instruction',
                     constraints=[(self.mock_constraint())])

    def test_should_return_specific_form_for_project_with_unique_id(self):
        dbm = Mock(spec=DatabaseManager)
        questionnaire_mock = MagicMock()
        field1 = self.text_field(code='code')
        questionnaire_mock.name = 'name'
        unique_id_field = UniqueIdField("clinic",
                                        "cl",
                                        "cl",
                                        "Clinic",
                                        instruction="")
        questionnaire_mock.fields = [field1, unique_id_field]
        questionnaire_mock.form_code = 'form_code'
        questionnaire_mock.id = 'id'

        questionnaire_mock.activeLanguages = ["en"]
        questionnaire_mock.entity_questions = [
            self.text_field(code='entity_question_code')
        ]
        questionnaire_mock.xform = None
        entity1 = Entity(dbm, short_code="shortCode1", entity_type="someType")
        entity1._doc.data['name'] = {'value': 'nameOfEntity'}
        entities = [entity1, entity1]
        with patch("mangrove.transport.xforms.xform.FormModel"
                   ) as form_model_mock:
            with patch("mangrove.form_model.field.get_all_entities"
                       ) as get_all_entities_mock:
                get_all_entities_mock.return_value = entities
                form_model_mock.get.return_value = questionnaire_mock
                actual_response = xform_for(dbm, "someFormId", 'rep1')
                self.assertTrue(
                    self.checker.check_output(
                        actual_response,
                        unicode(expected_xform_for_project_with_unique_id), 0),
                    actual_response)

    def test_should_escape_special_characters_from_requested_form(self):
        dbm = Mock()
        questionnaire_mock = Mock()
        field1 = SelectField(name='name&',
                             label='name&',
                             code='selectcode',
                             instruction='instruction&',
                             options=[{
                                 'text': 'option1&',
                                 'val': 'o1'
                             }])
        questionnaire_mock.name = '<mock_name'
        questionnaire_mock.fields = [field1]
        questionnaire_mock.form_code = 'form_code'
        questionnaire_mock.id = 'id'
        questionnaire_mock.unique_id_field = None
        questionnaire_mock.xform = None
        with patch("mangrove.transport.xforms.xform.FormModel"
                   ) as form_model_mock:
            form_model_mock.get.return_value = questionnaire_mock
            one_of_unicode_unknown_ = xform_for(dbm, "someFormId", 'rep1')
            expected = unicode(expected_xform_with_escaped_characters)
            self.assertTrue(
                self.checker.check_output(one_of_unicode_unknown_, expected,
                                          0))
Exemple #31
0
def assert_xml_equals(reference, result):
    """Compare if XML documents are equal except formatting."""
    checker = LXMLOutputChecker()
    if not checker.check_output(reference, result, 0):
        message = checker.output_difference(Example("", reference), result, 0)
        pytest.fail(message)