Esempio n. 1
0
 def test_serializeUnicode(self):
     """
     Test that unicode is encoded correctly in the appropriate places, and
     raises an error when it occurs in inappropriate place.
     """
     snowman = "\N{SNOWMAN}"
     self.assertFlattensImmediately(snowman, b"\xe2\x98\x83")
     self.assertFlattensImmediately(tags.p(snowman), b"<p>\xe2\x98\x83</p>")
     self.assertFlattensImmediately(Comment(snowman), b"<!--\xe2\x98\x83-->")
     self.assertFlattensImmediately(CDATA(snowman), b"<![CDATA[\xe2\x98\x83]]>")
     self.assertFlatteningRaises(Tag(snowman), UnicodeEncodeError)
     self.assertFlatteningRaises(
         Tag("p", attributes={snowman: ""}), UnicodeEncodeError
     )
Esempio n. 2
0
 def test_serializeUnicode(self):
     """
     Test that unicode is encoded correctly in the appropriate places, and
     raises an error when it occurs in inappropriate place.
     """
     snowman = u'\N{SNOWMAN}'
     return gatherResults([
         self.assertFlattensTo(snowman, '\xe2\x98\x83'),
         self.assertFlattensTo(tags.p(snowman), '<p>\xe2\x98\x83</p>'),
         self.assertFlattensTo(Comment(snowman), '<!--\xe2\x98\x83-->'),
         self.assertFlattensTo(CDATA(snowman), '<![CDATA[\xe2\x98\x83]]>'),
         self.assertFlatteningRaises(Tag(snowman), UnicodeEncodeError),
         self.assertFlatteningRaises(Tag('p', attributes={snowman: ''}),
                                     UnicodeEncodeError),
     ])
Esempio n. 3
0
 def test_formatRootTagNoFilename(self):
     """
     The C{_formatRoot} method formats a C{Tag} with no filename information
     as 'Tag <tagName>'.
     """
     e = self.makeFlattenerError()
     self.assertEqual(e._formatRoot(Tag('a-tag')), 'Tag <a-tag>')
Esempio n. 4
0
 def roots(self, request: object, tag: Tag) -> "Flattenable":
     r = []
     for o in self.system.rootobjects:
         r.append(tag.clone().fillSlots(root=tags.code(
             epydoc2stan.taglink(o, self.filename)
             )))
     return r
Esempio n. 5
0
    def head(self, request: IRequest, tag: Tag = tags.head) -> KleinRenderable:
        """
        <head> element.
        """
        urls = self.config.urls

        children = tag.children
        tag.children = []

        return tag(
            tags.meta(charset="utf-8"),
            tags.meta(name="viewport",
                      content="width=device-width, initial-scale=1"),
            tags.link(
                type="image/png",
                rel="icon",
                href=urls.logo.asText(),
            ),
            tags.link(
                type="text/css",
                rel="stylesheet",
                media="screen",
                href=urls.bootstrapCSS.asText(),
            ),
            tags.link(
                type="text/css",
                rel="stylesheet",
                media="screen",
                href=urls.styleSheet.asText(),
            ),
            tags.script(src=urls.jqueryJS.asText()),
            tags.script(src=urls.bootstrapJS.asText()),
            self.title(request),
            children,
        )
Esempio n. 6
0
 def names(self, request: object, tag: Tag) -> "Flattenable":
     def link(obj: model.Documentable) -> Tag:
         # The "data-type" attribute helps doc2dash figure out what
         # category (class, method, etc.) an object belongs to.
         attributes = {}
         if obj.kind:
             attributes["data-type"] = epydoc2stan.format_kind(obj.kind)
         return tags.code(
             epydoc2stan.taglink(obj, NameIndexPage.filename), **attributes
             )
     name2obs: DefaultDict[str, List[model.Documentable]] = defaultdict(list)
     for obj in self.initials[self.my_letter]:
         name2obs[obj.name].append(obj)
     r = []
     for name in sorted(name2obs, key=lambda x:(x.lower(), x)):
         item: Tag = tag.clone()(name)
         obs = name2obs[name]
         if all(isPrivate(ob) for ob in obs):
             item(class_='private')
         if len(obs) == 1:
             item(' - ', link(obs[0]))
         else:
             ul = tags.ul()
             for ob in sorted(obs, key=_lckey):
                 subitem = tags.li(link(ob))
                 if isPrivate(ob):
                     subitem(class_='private')
                 ul(subitem)
             item(ul)
         r.append(item)
     return r
Esempio n. 7
0
    def test_missing(self):
        """
        minimally-defined static servers just need anonymous-storage-FURL
        and permutation-seed-base32. The WUI used to have problems
        rendering servers that lacked nickname and version. This tests that
        we can render such minimal servers.
        """
        ann = {"anonymous-storage-FURL": "pb://w2hqnbaa25yw4qgcvghl5psa3srpfgw3@tcp:127.0.0.1:51309/vucto2z4fxment3vfxbqecblbf6zyp6x",
               "permutation-seed-base32": "w2hqnbaa25yw4qgcvghl5psa3srpfgw3",
               }
        srv = NativeStorageServer("server_id", ann, None, {}, EMPTY_CLIENT_CONFIG)
        srv.get_connection_status = lambda: ConnectionStatus(False, "summary", {}, 0, 0)

        class FakeClient(_Client):
            def __init__(self):
                service.MultiService.__init__(self)
                self.storage_broker = StorageFarmBroker(
                    permute_peers=True,
                    tub_maker=None,
                    node_config=EMPTY_CLIENT_CONFIG,
                )
                self.storage_broker.test_add_server("test-srv", srv)

        root = RootElement(FakeClient(), time.time)
        req = DummyRequest(b"")
        tag = Tag(b"")

        # Pick all items from services table.
        items = root.services_table(req, tag).item(req, tag)

        # Coerce `items` to list and pick the first item from it.
        item = list(items)[0]

        self.assertEqual(item.slotData.get("version"), "")
        self.assertEqual(item.slotData.get("nickname"), "")
Esempio n. 8
0
    async def _events(self,
                      request: IRequest,
                      tag: Tag,
                      reverse_order: bool = False) -> KleinRenderable:
        if reverse_order:

            def order(i: Iterable) -> Iterable:
                return reversed(sorted(i))

        else:

            def order(i: Iterable) -> Iterable:
                return sorted(i)

        authorizationsForUser = partial(
            self.config.authProvider.authorizationsForUser, request.user)

        relevantAuthorizations = (Authorization.readIncidents
                                  | Authorization.writeIncidentReports)

        eventIDs = order([
            event.id for event in await self.config.store.events()
            if relevantAuthorizations & await authorizationsForUser(event)
        ])

        if eventIDs:
            eventPage = self.config.urls.viewEvent.asText()
            return (tag.clone()(tags.a(eventID,
                                       href=eventPage.replace(
                                           "<eventID>", eventID)))
                    for eventID in eventIDs)
        else:
            return tag("No events found.")
Esempio n. 9
0
 def onlyIfOneRoot(self, request: object, tag: Tag) -> "Flattenable":
     if len(self.system.rootobjects) != 1:
         return []
     else:
         root, = self.system.rootobjects
         return tag.clear()(
             "Start at ", tags.code(epydoc2stan.taglink(root, self.filename)),
             ", the root ", epydoc2stan.format_kind(root.kind).lower(), ".")
Esempio n. 10
0
 def title(self, request: IRequest, tag: Tag) -> KleinRenderable:
     """
     `<title>` element.
     """
     if self.titleText is None:
         return tag
     else:
         return tag.clone()(self.titleText)
Esempio n. 11
0
 def title(self, request: IRequest, tag: Tag) -> KleinRenderable:
     """
     `<title>` element.
     """
     if self.name is None:
         return tag
     else:
         return tag.clone()(self.name)
Esempio n. 12
0
 def test_suffix(self):
     """
     L{Tag.__call__} accepts Python keywords with a suffixed underscore as
     the DOM attribute of that literal suffix.
     """
     proto = Tag('div')
     tag = proto()
     tag(class_='a')
     self.assertEquals(tag.attributes, {'class': 'a'})
Esempio n. 13
0
    def root(self, request: IRequest, tag: Tag) -> KleinRenderable:
        """
        Root element.
        """
        user = getattr(request, "user", None)
        if user is None:
            username = "******"
        else:
            try:
                username = user.shortNames[0]
            except IndexError:
                username = "******"

        slots = dict(user=username)

        tag.fillSlots(**slots)

        return tag
Esempio n. 14
0
 def test_formatRootTagWithFilename(self):
     """
     The C{_formatRoot} method formats a C{Tag} with filename information
     using the filename, line, column, and tag information
     """
     e = self.makeFlattenerError()
     t = Tag('a-tag', filename='tpl.py', lineNumber=10, columnNumber=20)
     self.assertEqual(e._formatRoot(t),
                      'File "tpl.py", line 10, column 20, in "a-tag"')
Esempio n. 15
0
 def test_suffix(self) -> None:
     """
     L{Tag.__call__} accepts Python keywords with a suffixed underscore as
     the DOM attribute of that literal suffix.
     """
     proto = Tag("div")
     tag = proto()
     tag(class_="a")
     self.assertEqual(tag.attributes, {"class": "a"})
Esempio n. 16
0
 def kind(self, request: object, tag: Tag) -> Tag:
     child = self.child
     kind = child.kind
     assert kind is not None  # 'kind is None' makes the object invisible
     kind_name = epydoc2stan.format_kind(kind)
     if isinstance(child, Function) and child.is_async:
         # The official name is "coroutine function", but that is both
         # a bit long and not as widely recognized.
         kind_name = f'Async {kind_name}'
     return tag.clear()(kind_name)
Esempio n. 17
0
 def test_tagWithoutLocation(self):
     """
     If a L{FlattenerError} is created with a L{Tag} instance without source
     location information, only the tagName is included in the string
     representation of the exception.
     """
     self.assertEqual(
         str(FlattenerError(RuntimeError("reason"), [Tag("span")], [])),
         "Exception while flattening:\n" "  Tag <span>\n" "RuntimeError: reason\n",
     )
Esempio n. 18
0
 def running_experiment(self, request, tag):
     if len(self.running_experiments):
         for expt in self.running_experiments:
             yield tag.clone().fillSlots(
                 url="/experiment/{:s}".format(expt.id),
                 title=expt.sketch.title,
                 duration=str(
                     datetime.timedelta(seconds=int(time.time() -
                                                    expt.startTime))))
     else:
         yield Tag('div',
                   children=['No running experiments'],
                   attributes={'class': 'list-group-item'})
Esempio n. 19
0
 def baseTables(self, request: object, item: Tag) -> "Flattenable":
     baselists = self.baselists[:]
     if not baselists:
         return []
     if baselists[0][0][0] == self.ob:
         del baselists[0]
     loader = ChildTable.lookup_loader(self.template_lookup)
     return [
         item.clone().fillSlots(baseName=self.baseName(b),
                                baseTable=ChildTable(
                                    self.docgetter, self.ob,
                                    sorted(attrs, key=objects_order),
                                    loader)) for b, attrs in baselists
     ]
Esempio n. 20
0
    def test_tag(self):
        """
        If a L{FlattenerError} is created with a L{Tag} instance with source
        location information, the source location is included in the string
        representation of the exception.
        """
        tag = Tag("div", filename="/foo/filename.xhtml", lineNumber=17, columnNumber=12)

        self.assertEqual(
            str(FlattenerError(RuntimeError("reason"), [tag], [])),
            "Exception while flattening:\n"
            '  File "/foo/filename.xhtml", line 17, column 12, in "div"\n'
            "RuntimeError: reason\n",
        )
Esempio n. 21
0
    def head(self, request: IRequest, tag: Tag) -> KleinRenderable:
        """
        `<head>` element.
        """
        urls = self.config.urls

        children = tag.children
        tag.children = []

        imports = (tags.script(src=url.asText())
                   for url in self.urlsFromImportSpec(
                       tag.attributes.get("imports", "")))

        if "imports" in tag.attributes:
            del tag.attributes["imports"]

        return tag(
            # Resource metadata
            tags.meta(charset="utf-8"),
            tags.meta(name="viewport",
                      content="width=device-width, initial-scale=1"),
            tags.link(
                type="image/png",
                rel="icon",
                href=urls.logo.asText(),
            ),
            tags.link(
                type="text/css",
                rel="stylesheet",
                media="screen",
                href=urls.bootstrapCSS.asText(),
            ),
            tags.link(
                type="text/css",
                rel="stylesheet",
                media="screen",
                href=urls.styleSheet.asText(),
            ),
            self.title(request, tags.title.clone()),
            # JavaScript resource imports
            imports,
            # Child elements
            children,
        )
Esempio n. 22
0
    def head(self, request: IRequest, tag: Tag) -> KleinRenderable:
        """
        `<head>` element.
        """
        urls = self.config.urls

        children = tag.children
        tag.children = []

        imports = (
            tags.script(src=url.asText())
            for url in
            self.urlsFromImportSpec(tag.attributes.get("imports", ""))
        )

        if "imports" in tag.attributes:
            del tag.attributes["imports"]

        return tag(
            # Resource metadata
            tags.meta(charset="utf-8"),
            tags.meta(
                name="viewport", content="width=device-width, initial-scale=1"
            ),
            tags.link(
                type="image/png", rel="icon",
                href=urls.logo.asText(),
            ),
            tags.link(
                type="text/css", rel="stylesheet", media="screen",
                href=urls.bootstrapCSS.asText(),
            ),
            tags.link(
                type="text/css", rel="stylesheet", media="screen",
                href=urls.styleSheet.asText(),
            ),
            self.title(request, tags.title.clone()),
            # JavaScript resource imports
            imports,
            # Child elements
            children,
        )
Esempio n. 23
0
    def url(self, request: IRequest, tag: Tag) -> KleinRenderable:
        """
        Look up a URL with the name specified by the given tag's C{"url"}
        attribute, which will be removed.
        If the tag has an C{"attr"} attribute, remove it and add the URL to the
        tag in the attribute named by the (removed) C{"attr"} attribute and
        return the tag.
        For C{"a"} tags, C{"attr"} defaults to C{"href"}.
        For C{"img"} tags, C{"attr"} defaults to C{"src"}.
        If the C{"attr"} attribute is defined C{""}, return the URL as text.
        """
        name = tag.attributes.pop("url", None)

        if name is None:
            raise ValueError("Rendered URL must have a url attribute")

        try:
            url = getattr(self.config.urls, name)
        except AttributeError:
            raise ValueError(f"Unknown URL name: {name}")

        text = url.asText()

        if tag.tagName == "json":
            return jsonTextFromObject(text)

        attributeName = tag.attributes.pop("attr", None)
        if attributeName is None:
            if tag.tagName in ("a", "link"):
                attributeName = "href"
            elif tag.tagName in ("script", "img"):
                attributeName = "src"
            else:
                raise ValueError("Rendered URL must have an attr attribute")

        if attributeName == "":
            return text
        else:
            tag.attributes[attributeName] = text
            return tag
Esempio n. 24
0
 def heading(self, request: object, tag: Tag) -> Tag:
     return tag.clear()("Summary of Undocumented Objects")
 def destination(self, request: IRequest, tag: Tag) -> str:
     """
     JSON string: URL for the redirect destination.
     """
     return tag.fillSlots(destination_url=self.location.asText())
Esempio n. 26
0
 def renderMethod(
     self, request: Optional[IRequest], tag: Tag
 ) -> Flattenable:
     return tag.fillSlots(test2="world.")
Esempio n. 27
0
 def heading(self, request: object, tag: Tag) -> Tag:
     return tag.clear()("Index of Names")
Esempio n. 28
0
 def rootkind(self, request: object, tag: Tag) -> Tag:
     return tag.clear()('/'.join(sorted(
          epydoc2stan.format_kind(o.kind, plural=True).lower()
          for o in self.system.rootobjects
          )))
Esempio n. 29
0
 def fillSlot(tag: Tag) -> Tag:
     return tag.fillSlots(stuff=toss.pop())
Esempio n. 30
0
def proto(*a, **kw):
    """
    Produce a new tag for testing.
    """
    return Tag('hello')(*a, **kw)
Esempio n. 31
0
def proto(*a: Flattenable, **kw: Flattenable) -> Tag:
    """
    Produce a new tag for testing.
    """
    return Tag("hello")(*a, **kw)
Esempio n. 32
0
 def destination(self, request: IRequest, tag: Tag) -> str:
     """
     JSON string: URL for the redirect destination.
     """
     return cast(str, tag.fillSlots(destination_url=self.location.asText()))
Esempio n. 33
0
 def stuff(self, request: object, tag: Tag) -> Tag:
     tag.clear()
     tag([moduleSummary(o, self.filename) for o in self.system.rootobjects])
     return tag