"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/qpy/test/utest_xml.py $
$Id: utest_xml.py 31098 2008-09-15 19:28:18Z dbinger $
"""
from sancho.utest import UTest
from qpy import xml, xml_quote
import sys

if sys.version.startswith("3"):
    unicode_string = str
else:
    from __builtin__ import unicode as unicode_string


class TestXml (UTest):

    def test_xml(self):
        u = xml()
        assert str(u) == ''
        assert u == xml('')
        assert u == xml(None)
        assert u == ''
        assert xml('<') == '<'
        assert xml_quote('<') == '&lt;'
        u += 1
        u += None
        assert u == '1'
        assert xml('a%s') % '&' == 'a&amp;'
        assert xml('a%(a)s%(b)s') % dict(a='&', b=xml('<')) == 'a&amp;<'
        assert xml('a%s%s') % ('&', xml('<')) == 'a&amp;<'
        t = (1,2)
        try:
            t += u
            assert 0
        except TypeError:
            pass
        t = []
        t += u
        assert t == list(u)

    def test_a(self):
        s = xml('<') + '<'
        assert isinstance(s, xml) and s == '<&lt;'
        s = '<' + xml('<')
        assert isinstance(s, xml) and s == '&lt;<', '__radd__ not working.'
        s = xml('%s') % '<'
        assert isinstance(s, xml) and  s == '&lt;'
        s = xml('%s') % xml('<')
        assert isinstance(s, xml) and s == '<'
        s = xml('%(a)s') % dict(a='<')
        assert isinstance(s, xml) and s == '&lt;'
        s = unicode_string('%s') % xml('a')
        assert isinstance(s, unicode_string)
        assert s == 'a'
        s = xml('a')
        s += '<'
        assert s == 'a&lt;'

    def test_quote_wrapper(self):
        assert xml("%0.2f") % 2 == '2.00'
        assert type(xml("%0.2f") % 2) is xml
        assert xml("%(a)s %(b)0.2f") % dict(
            a=unicode_string('<'), b=2) == '&lt; 2.00'
        assert type(xml("%(a)s %(b)0.2f") % dict(
            a=unicode_string('a'), b=2)) is xml
        if str is not unicode_string:
            assert xml("%(a)r %(b)0.2f") % dict(
                a=unicode_string('<'), b=2) == "u&#39;&lt;&#39; 2.00"
        else:
            print(repr(xml("%(a)r %(b)0.2f") % dict(
                a=unicode_string('<'), b=2)))
            assert xml("%(a)r %(b)0.2f") % dict(
                a=unicode_string('<'), b=2) == "&#39;&lt;&#39; 2.00"
        assert type(xml("%(a)r %(b)0.2f")) is xml

    def test_pickle(self):
        from pickle import loads, dumps
        s = xml('hello')
        assert s == loads(dumps(xml(s), 2))

if __name__ == '__main__':
    TestXml()
