Exemple #1
0
 def convert(self, converter):
     size = self["href"].convert(converter).contentlength(
         root=converter.root)
     if size is not None:
         return xsc.Text(size)
     else:
         return xsc.Text("?")
Exemple #2
0
def test_with_addattr():
    with xsc.build():
        with html.ul() as e:
            with xsc.addattr("id"):
                +xsc.Text("gurk")
    assert e == html.ul(id="gurk")

    with xsc.build():
        with html.ul() as e:
            with xsc.addattr(html.ul.Attrs.id):
                +xsc.Text("gurk")
    assert e == html.ul(id="gurk")
 def convert(self, converter):
     with xsc.build():
         with xsc.Frag() as e:
             if self[term] or self[classifier]:
                 with doc.dt():
                     +xsc.Frag(self[term])
                     if self[classifier]:
                         +xsc.Text(" (")
                         +xsc.Frag(self[classifier]).withsep(", ")
                         +xsc.Text(")")
             +xsc.Frag(self[definition])
     return e.convert(converter)
Exemple #4
0
def test_with():
    with xsc.build():
        with html.ul() as e:
            +html.li(1)
            +html.li(2)
    assert e == html.ul(html.li(1), html.li(2))

    with xsc.build():
        with html.p() as e:
            +html.span(1)
            with html.b():
                +html.span(2)
            +html.span(3)
    assert e == html.p(html.span(1), html.b(html.span(2)), html.span(3))

    with xsc.build():
        with html.p() as e:
            +xsc.Text(1)
    assert e == html.p(1)

    with xsc.build():
        with html.p() as e:
            +xml.Attrs(lang="de")
    assert e == html.p(xml.Attrs(lang="de"))
    assert e.bytes() == b'<p xml:lang="de"></p>'

    with xsc.build():
        with xsc.Frag() as e:
            +xsc.Text(1)
    assert e == xsc.Frag(1)

    # Test add()
    with xsc.build():
        with html.p() as e:
            xsc.add(1)
    assert e == html.p(1)

    with xsc.build():
        with html.p() as e:
            xsc.add(class_="foo")
    assert e == html.p(class_="foo")

    with xsc.build():
        with html.p() as e:
            xsc.add({"class": "foo"})
    assert e == html.p(class_="foo")

    with xsc.build():
        with html.p() as e:
            xsc.add(xml.Attrs(lang="en"))
    assert e == html.p(xml.Attrs(lang="en"))
def test_text():
	with xsc.build():
		with xsc.Frag() as e:
			+detox.def_("gurk()")
			+xsc.Text("foo")
			+detox.end("def")
	assert makeoutput(e, "gurk") == "foo"
def test_publishescaped():
    s = """\x04<&'"\xff>"""
    node = xsc.Text(s)
    assert node.bytes(encoding="ascii") == b"""&#4;&lt;&amp;'"&#255;&gt;"""
    node = html.span(class_=s)
    assert node.bytes(
        encoding="ascii",
        xhtml=2) == b"""<span class="&#4;&lt;&amp;'&quot;&#255;&gt;"/>"""
def test_scopecheck():
	with xsc.build():
		with xsc.Frag() as e:
			+detox.def_("gurk()")
			+xsc.Text("hurz")
			+detox.end()

	assert makeoutput(e, "gurk") == "hurz"

	with xsc.build():
		with xsc.Frag() as e:
			+detox.def_("gurk()")
			+xsc.Text("hurz")
			+detox.end("for")

	with pytest.raises(SyntaxError):
		makeoutput(e, "gurk")
Exemple #8
0
def test_getitem():
    for cls in (xsc.Frag, html.div):
        e = cls(list(range(6)))
        # int
        assert e[2] == xsc.Text(2)
        assert e[-1] == xsc.Text(5)

        # slice
        assert e[:] == cls(list(range(6)))
        assert e[:2] == cls(0, 1)
        assert e[-2:] == cls(4, 5)
        assert e[::2] == cls(0, 2, 4)
        assert e[1::2] == cls(1, 3, 5)
        assert e[::-1] == cls(list(range(5, -1, -1)))

        # selector
        e = cls((html.dt(i), html.dd(2 * i)) for i in range(3))
        assert xsc.Frag(e[html.dt]) == xsc.Frag(html.dt(0), html.dt(1),
                                                html.dt(2))
        assert xsc.Frag(e[html.dt[1]]) == xsc.Frag(html.dt(1))
        assert e[e[0]][0] is e[
            0]  # selector for a single node (returns an iterator nevertheless)

        def isgt1(p):
            return int(str(p[-1])) > 1

        assert xsc.Frag(e[html.dt & isgt1]) == xsc.Frag(html.dt(2))
        assert xsc.Frag(e[e / html.dt]) == xsc.Frag(html.dt(0), html.dt(1),
                                                    html.dt(2))
        assert xsc.Frag(e[e.__class__ / html.dt]) == xsc.Frag(
            html.dt(0), html.dt(1), html.dt(2))

        for attr in ("class_", xml.Attrs.lang):
            e = cls("foo", html.div("bar", {attr: "gurk"}), "baz")
            i = e[xsc.Text]
            assert str(next(i)) == "foo"
            assert str(next(i)) == "baz"
            with pytest.raises(StopIteration):
                next(i)

        # list
        for attr in ("class", xml.Attrs.lang):
            node = cls(html.div("foo", html.div("bar", {attr: "gurk"}), "baz"))
            assert node[[]] is node
            assert str(node[[0, 1]]) == "bar"
            assert str(node[[0, 1, attr]]) == "gurk"
Exemple #9
0
    def convert(self, converter):
        format = str(self["format"].convert(converter))
        if "utc" in self.attrs:
            f = datetime.datetime.utcnow
        else:
            f = datetime.datetime.now

        return xsc.Text(f().strftime(format))
Exemple #10
0
 def convert(self, converter):
     if "len" in self.attrs:
         chars = int(self["len"].convert(converter))
         count = (chars + len(self.text) - 1) // len(self.text)
         text = count * self.text
         text = text[:chars]
     else:
         text = self.text.strip()
     return xsc.Text(text)
Exemple #11
0
	def text(self, data):
		node = xsc.Text(data)
		if self.loc:
			node.startloc = xsc.Location(self._url, *self._position)
		node.parsed(self, "text")
		if self._inattr:
			self._stack[-1].append(node)
		elif not self._indoctype:
			return ("textnode", node)
 def toxist(node):
     if isinstance(node, nodes.Text):
         return xsc.Text(str(node.astext()))
     else:
         e = elements[node.__class__.__name__](toxist(child)
                                               for child in node.children)
         e.startloc = xsc.Location(node.source, node.line)
         for (attrkey, attrvalue) in node.attlist():
             if attrkey in e.Attrs:
                 if isinstance(attrvalue, list):
                     attrvalue = " ".join(attrvalue)
                 e.attrs[attrkey] = attrvalue
         return e
Exemple #13
0
def translate(txt, context):
    """
    Someday soon, this function will return a translation for unicode_string
    suitable for context.

       - If txt is a unicode string it will translate it and return a
         xsc.Text instance to be used with xist
       - If a xist DOM tree is supplied, it will recursively traverse it
         and translate B{all} CharachterData instance's content that are not
         marked with a __translated__ Flag.
         
    """
    if type(txt) == UnicodeType:
        # insert actual translation here!!

        ret = xsc.Text(txt)
        ret.__translated__ = True
        return ret

    elif type(txt) == StringType:
        return translate(unicode(txt), context)

    elif isinstance(txt, xsc.Text):
        if getattr(txt, "__translated__", False):
            return txt
        else:
            return translate(txt.content, context)

    elif isinstance(txt, xsc.Frag):
        for index, a in enumerate(txt):
            txt[index] = translate(txt[index], context)

    elif isinstance(txt, xsc.Element):
        txt.content = translate(txt.content, context)

    else:
        tpl = (
            repr(type(txt)),
            repr(txt),
        )
        raise TypeError("translate can only operate on unicode strings, "+ \
                        "xsc.Element, or xsc.Frag, not %s %s" % tpl)
def test_texteq():
	assert xsc.Text() == xsc.Text()
	assert xsc.Text(1) == xsc.Text(1)
	assert xsc.Text("1") == xsc.Text(1)
	assert xsc.Text("1") == xsc.Text(1)
	assert xsc.Text("") != xsc.Text(1)
 def convert(self, node):
     if isinstance(node, nodes.document):
         return xsc.Frag(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.Text):
         return xsc.Text(node.astext())
     elif isinstance(node, nodes.problematic):
         # We don't do anything about this
         return xsc.Frag(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.section):
         return self.doc.section(
             self.convert(child) for child in node.children)
     elif isinstance(node, nodes.title):
         return self.doc.h(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.paragraph):
         return self.doc.p(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.bullet_list):
         return self.doc.ul(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.list_item):
         return self.doc.li(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.definition_list):
         return self.doc.dl(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.definition_list_item):
         return xsc.Frag(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.term):
         return self.doc.dt(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.definition):
         return self.doc.dd(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.literal_block):
         return self.doc.prog(
             self.convert(child) for child in node.children)
     elif isinstance(node, nodes.literal):
         return self.doc.lit(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.emphasis):
         return self.doc.em(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.substitution_reference):
         try:
             return getattr(self.abbr, node.attributes["refname"].lower())()
         except AttributeError:
             return xsc.Frag(self.convert(child) for child in node.children)
     elif isinstance(node, nodes.reference):
         e = self.doc.a(self.convert(child) for child in node.children)
         if "anonymous" in node.attributes:
             self.unnamedrefs.append(e)
         else:
             self.namedrefs[node.attributes["refname"]].append(e)
         return e
     elif isinstance(node, nodes.target):
         uri = node.attributes["refuri"]
         if "anonymous" in node.attributes:
             # Set the link on the first unnamed reference
             self.unnamedrefs[0].attrs.href = uri
             del self.unnamedrefs[0]  # done => remove it
         else:
             for name in node.attributes["names"]:
                 try:
                     es = self.namedrefs[name]
                 except KeyError:
                     pass
                 else:
                     for e in es:
                         e.attrs.href = uri
                     del self.namedrefs[name]
         return xsc.Null
     elif isinstance(node, nodes.system_message):
         warnings.warn(ReSTConversionWarning(str(node)))
         return xsc.Null  # ignore system messages
     else:
         raise TypeError("can't handle {!r}".format(node.__class__))
Exemple #16
0
 def convert(self, converter):
     format = str(self["format"].convert(converter))
     return xsc.Text(self["href"].convert(converter).lastmodified(
         root=converter.root).strftime(format))
def test_mixeq():
	assert xsc.Comment(1) != xsc.Text(1)
	assert xsc.DocType(1) != xsc.Text(1)
Exemple #18
0
def getdoc(thing, format):
    if thing.__doc__ is None:
        return xsc.Null

    # Remove indentation
    lines = textwrap.dedent(thing.__doc__).split("\n")

    # remove empty lines
    while lines and not lines[0]:
        del lines[0]
    while lines and not lines[-1]:
        del lines[-1]

    text = "\n".join(lines)

    modulename = _getmodulename(thing)
    if inspect.ismethod(thing):
        base = f"METHOD-DOCSTRING({modulename}.{thing.__class__.__name__}.{thing.__qualname__})"
    elif isinstance(thing, property):
        base = f"PROPERTY-DOCSTRING({modulename}.{thing})"
    elif inspect.isfunction(thing):
        base = f"FUNCTION-DOCSTRING({modulename}.{thing.__qualname__})"
    elif inspect.isclass(thing):
        base = f"CLASS-DOCSTRING({modulename}.{thing.__qualname__})"
    elif inspect.ismodule(thing):
        base = f"MODULE-DOCSTRING({modulename})"
    else:
        base = "DOCSTRING"

    lformat = format.lower()
    if lformat == "plaintext":
        return xsc.Text(text)
    elif lformat == "restructuredtext":
        from ll.xist.ns import rest, doc
        return rest.fromstring(text, base=base).conv(target=doc)
    elif lformat == "xist":
        from ll.xist.ns import doc
        node = parse.tree(parse.String(text), parse.SGMLOP(), parse.NS(doc),
                          parse.Node(pool=xsc.docpool(), base=base))
        if not node[
                p]:  # optimization: one paragraph docstrings don't need a <p> element.
            node = p(node)

        if inspect.ismethod(thing):
            # Use the original method instead of the decorator
            realthing = thing
            while hasattr(realthing, "__wrapped__"):
                realthing = realthing.__wrapped__
            for ref in node.walknodes(pyref):
                if "module" not in ref.attrs:
                    ref["module"] = _getmodulename(realthing)
                    if "class_" not in ref.attrs:
                        ref["class_"] = thing.__self__.__class__.__name__
                        if "method" not in ref.attrs:
                            ref["method"] = thing.__name__
        elif inspect.isfunction(thing):
            # Use the original method instead of the decorator
            while hasattr(thing, "__wrapped__"):
                thing = thing.__wrapped__
            for ref in node.walknodes(pyref):
                if "module" not in ref.attrs:
                    ref["module"] = _getmodulename(thing)
        elif inspect.isclass(thing):
            for ref in node.walknodes(pyref):
                if "module" not in ref.attrs:
                    ref["module"] = _getmodulename(thing)
                    if "class_" not in ref.attrs:
                        ref["class_"] = thing.__name__
        elif inspect.ismodule(thing):
            for ref in node.walknodes(pyref):
                if "module" not in ref.attrs:
                    ref["module"] = thing.__name__
        return node
    else:
        raise ValueError(f"unsupported __docformat__ {format!r}")
Exemple #19
0
def test_charref():
    node = chars.ouml()
    hash(node)
    assert len(node) == 1
    assert node[0] == xsc.Text("ö")
    assert 3 * node == xsc.Text("ööö")
    assert node * 3 == xsc.Text("ööö")
    assert node[1:-2] == xsc.Text()
    assert node.capitalize() == xsc.Text("Ö")
    assert node.center(5) == xsc.Text("  ö  ")
    assert node.count("t") == 0
    assert node.endswith("ö") is True
    assert node.index("ö") == 0
    assert node.isalpha() is True
    assert node.isalnum() is True
    assert node.isdecimal() is False
    assert node.isdigit() is False
    assert node.islower() is True
    assert node.isnumeric() is False
    assert node.isspace() is False
    assert node.istitle() is False
    assert node.isupper() is False
    assert node.ljust(3) == xsc.Text("ö  ")
    assert node.ljust(3, ".") == xsc.Text("ö..")
    assert node.lower() == xsc.Text("ö")
    assert node.replace("ö", "x") == xsc.Text("x")
    assert node.rjust(3) == xsc.Text("  ö")
    assert node.rjust(3, ".") == xsc.Text("..ö")
    assert node.rfind("ö") == 0
    assert node.rindex("ö") == 0
    assert node.startswith("ö") is True
    assert node.swapcase() == xsc.Text("Ö")
    assert node.title() == xsc.Text("Ö")
    assert node.upper() == xsc.Text("Ö")
def test_textcomment():
    pool = xsc.Pool()
    assert pool.text("foo") == xsc.Text("foo")
    assert pool.comment("foo") == xsc.Comment("foo")
Exemple #21
0
def test_text():
    s = "test"
    node = xsc.Text(s)
    hash(node)
    assert len(node), 4
    assert node[1] == xsc.Text("e")
    assert 3 * node == xsc.Text(3 * s)
    assert node * 3 == xsc.Text(s * 3)
    assert node[1:3] == xsc.Text("es")
    assert node.capitalize() == xsc.Text("Test")
    assert node.center(8) == xsc.Text("  test  ")
    assert node.count("t") == 2
    assert node.endswith("st") is True
    assert node.index("s") == 2
    assert node.isalpha() is True
    assert node.isalnum() is True
    assert node.isdecimal() is False
    assert node.isdigit() is False
    assert node.islower() is True
    assert node.isnumeric() is False
    assert node.isspace() is False
    assert node.istitle() is False
    assert node.isupper() is False
    assert node.join(xsc.Frag(list("abc"))) == xsc.Frag(
        "a", "test", "b", "test", "c")
    assert node.ljust(6) == xsc.Text("test  ")
    assert node.ljust(6, ".") == xsc.Text("test..")
    assert node.lower() == xsc.Text("test")
    assert xsc.Text("  test").lstrip() == xsc.Text("test")
    assert node.replace("s", "x") == xsc.Text("text")
    assert node.rjust(6) == xsc.Text("  test")
    assert node.rjust(6, ".") == xsc.Text("..test")
    assert xsc.Text("test  ").rstrip() == xsc.Text("test")
    assert node.rfind("s") == 2
    assert node.rindex("s") == 2
    assert node.split("e") == xsc.Frag("t", "st")
    assert xsc.Text("a\nb\n").splitlines() == xsc.Frag("a", "b")
    assert node.startswith("te") is True
    assert xsc.Text("  test  ").strip() == xsc.Text("test")
    assert node.swapcase() == xsc.Text("TEST")
    assert node.title() == xsc.Text("Test")
    assert node.upper() == xsc.Text("TEST")
Exemple #22
0
 def convert_fo(self, converter):
     return xsc.Text(str(self.content))
def test_css():
    with xsc.build():
        with html.div(id=1) as e:
            with html.ul(id=2):
                +html.li("foo")
                +html.li()

    assert list(e.walknodes(css.selector("div"))) == [e]
    assert list(e.walknodes(css.selector("li"))) == [e[0][0], e[0][1]]
    assert list(e.walknodes(css.selector("div#1"))) == [e]
    assert list(e.walknodes(css.selector("#2"))) == [e[0]]
    assert list(e.walknodes(css.selector(":empty"))) == [e[0][1]]
    assert list(e.walknodes(css.selector("li:empty"))) == [e[0][1]]
    assert list(e.walknodes(css.selector("div :empty"))) == [e[0][1]]
    assert list(e.walknodes(css.selector("div>*:empty"))) == []
    assert list(e.walknodes(css.selector("div>:empty"))) == []
    assert list(e.walknodes(css.selector("*|li"))) == [e[0][0], e[0][1]]
    assert list(e.walknodes(css.selector("h|li",
                                         prefixes={"h": html
                                                   }))) == [e[0][0], e[0][1]]
    assert list(e.walknodes(css.selector("h|li", prefixes={"h":
                                                           specials}))) == []

    with xsc.build():
        with xsc.Frag() as e:
            +html.div("foo")
            +xsc.Text("filler")
            +html.p("foo")
            +xsc.Text("filler")
            +html.ul(html.li("foo"))

    assert list(e.walknodes(css.selector("div + p"))) == [e[2]]
    assert list(e.walknodes(css.selector("div + ul"))) == []
    assert list(e.walknodes(css.selector("ul + p"))) == []
    assert list(e.walknodes(css.selector("div ~ p"))) == [e[2]]
    assert list(e.walknodes(css.selector("div ~ ul"))) == [e[4]]
    assert list(e.walknodes(css.selector("p ~ div"))) == []
    assert list(e.walknodes(css.selector("div:first-child + p"))) == [e[2]]
    assert list(e.walknodes(css.selector("*:first-child + p"))) == [e[2]]

    with xsc.build():
        with xsc.Frag() as e:
            +html.span(html.b("hurz"), "gurk", html.em("hinz"),
                       html.em("kunz"))
            +html.em("hurz")
            +html.em("hinz")
            +xsc.Text("nix")
            +html.i("kunz")

    assert list(e.walknodes(
        css.selector("*:only-of-type"))) == [e[0], e[0][0], e[4]]
    assert list(e.walknodes(css.selector("*:nth-child(1)"))) == [e[0], e[0][0]]
    assert list(e.walknodes(css.selector("*:nth-child(2)"))) == [e[0][2], e[1]]
    assert list(e.walknodes(
        css.selector("*:nth-last-child(1)"))) == [e[0][3], e[4]]
    assert list(e.walknodes(
        css.selector("*:nth-last-child(2)"))) == [e[0][2], e[2]]
    assert list(e.walknodes(css.selector("*:nth-of-type(1)"))) == [
        e[0], e[0][0], e[0][2], e[1], e[4]
    ]
    assert list(e.walknodes(
        css.selector("*:nth-of-type(2)"))) == [e[0][3], e[2]]
    assert list(e.walknodes(css.selector("*:nth-last-of-type(1)"))) == [
        e[0], e[0][0], e[0][3], e[2], e[4]
    ]
    assert list(e.walknodes(
        css.selector("*:nth-last-of-type(2)"))) == [e[0][2], e[1]]

    e = xsc.Frag(html.span(html.b("hurz"), "gurk"))
    assert list(e.walknodes(css.selector("*:only-child"))) == [e[0], e[0][0]]

    with xsc.build():
        with xsc.Frag() as e:
            +html.em(class_="gurk", lang="en")
            +html.em(class_="gurk hurz", lang="en-us")
            +html.em(class_="hurz", lang="de")

    assert list(e.walknodes(css.selector("em[class='gurk']"))) == [e[0]]
    assert list(e.walknodes(css.selector("em[class~='gurk']"))) == [e[0], e[1]]
    assert list(e.walknodes(css.selector("em[lang|='en']"))) == [e[0], e[1]]