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 )
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), ])
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>')
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
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, )
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
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"), "")
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.")
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(), ".")
def title(self, request: IRequest, tag: Tag) -> KleinRenderable: """ `<title>` element. """ if self.titleText is None: return tag else: return tag.clone()(self.titleText)
def title(self, request: IRequest, tag: Tag) -> KleinRenderable: """ `<title>` element. """ if self.name is None: return tag else: return tag.clone()(self.name)
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'})
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
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"')
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"})
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)
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", )
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'})
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 ]
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", )
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, )
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, )
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
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())
def renderMethod( self, request: Optional[IRequest], tag: Tag ) -> Flattenable: return tag.fillSlots(test2="world.")
def heading(self, request: object, tag: Tag) -> Tag: return tag.clear()("Index of Names")
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 )))
def fillSlot(tag: Tag) -> Tag: return tag.fillSlots(stuff=toss.pop())
def proto(*a, **kw): """ Produce a new tag for testing. """ return Tag('hello')(*a, **kw)
def proto(*a: Flattenable, **kw: Flattenable) -> Tag: """ Produce a new tag for testing. """ return Tag("hello")(*a, **kw)
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()))
def stuff(self, request: object, tag: Tag) -> Tag: tag.clear() tag([moduleSummary(o, self.filename) for o in self.system.rootobjects]) return tag