def decode_structured(self, text, location): self.location = location if isinstance(location, pyglet.resource.FileLocation): doctree = publish_doctree(text, source_path=location.path) else: doctree = publish_doctree(text) self.decode_doctree(doctree)
def test_setup_fontpath2(self): with self.assertRaises(RuntimeError): directives.setup(format='SVG', fontpath='dummy.ttf', outputdir=self.tmpdir) text = (".. blockdiag::\n" "\n" " A -> B") publish_doctree(text)
def test_cleanup(self): directives.setup(format="SVG", outputdir=self.tmpdir, noviewbox=False) text = ".. actdiag::\n" "\n" " plugin autoclass\n" " A -> B" publish_doctree(text) from blockdiag import plugins self.assertEqual([], plugins.loaded_plugins)
def test_setup_fontpath1(self): with self.assertRaises(RuntimeError): directives.setup(format='SVG', fontpath=['dummy.ttf'], outputdir=self.tmpdir) text = (".. rackdiag::\n" "\n" " 1: server\n" " 2: database\n") publish_doctree(text)
def __call__( self, f ): # The following line is only good for its side effect of # filling self.f with the filtered content, that is why there # is no storage of the doctree. self.f.seek(0) self.f.truncate() core.publish_doctree(f.read()).traverse() self.f.seek(0) return self.f
def test_cleanup(self): directives.setup(format='SVG', outputdir=self.tmpdir, noviewbox=False) text = (".. rackdiag::\n" "\n" " plugin autoclass\n" " 1: server\n" " 2: database\n") publish_doctree(text) from blockdiag import plugins self.assertEqual([], plugins.loaded_plugins)
def test_setup_fontpath1(self): with self.assertRaises(RuntimeError): directives.setup(format='SVG', fontpath=['dummy.ttf'], outputdir=self.tmpdir) text = (".. nwdiag::\n" "\n" " network {" " A" " B" " }") publish_doctree(text)
def get_doc_strings(self): """collect docstrings in .py files in specified locations""" doc_strings = [] cnt = 0 opt = self.opt for loc in opt.location: for path, dummy, files in os.walk(loc): break # only want the first answer for file_name in sorted(files, key=lambda x:x.lower()): if not file_name.lower().endswith('.py'): continue file_path = os.path.join(path, file_name) doc_string = None src = open(file_path).read() src = src.replace('\r\n', '\n').replace('\r','\n')+'\n' try: ast_info = ast.parse(src) doc_string = ast.get_docstring(ast_info) except SyntaxError: doc_string = "**SYNTAX ERROR IN MODULE SOURCE**" if not doc_string and file_name != '__init__.py': doc_string = "**NO DOCSTRING**" if not doc_string: continue # don't whine about __init__.py if opt.show_paths: err("Processing: '%s'\n" % file_path) try: doc_tree = publish_doctree(doc_string) except SystemMessage: doc_tree = publish_doctree(""" Docutils could not parse docstring RST error level SEVERE/4 or higher in '%s'""" % file_path) doc_strings.append( (file_name, file_path, doc_tree) ) cnt += 1 if opt.max_files and cnt == opt.max_files: break return doc_strings
def test_cleanup(self): directives.setup(format='SVG', outputdir=self.tmpdir, noviewbox=False) text = (".. nwdiag::\n" "\n" " plugin autoclass\n" " network {" " A" " B" " }") publish_doctree(text) from blockdiag import plugins self.assertEqual([], plugins.loaded_plugins)
def parse(self, filename_or_file): try: filename = Path(filename_or_file) settings_overrides = dict(input_encoding='utf-8') doctree = publish_doctree(None, source_path=str(filename), source_class=FileInput, settings_overrides=settings_overrides, parser=self.parser_class()) except TypeError: filename = getattr(filename_or_file, 'name', None) doctree = publish_doctree(filename_or_file, source_class=FileInput, parser=self.parser_class()) return self.from_doctree(filename, doctree)
def parse_methods(methods): """Parse methods extract docstring and parse dockstring to get parameters """ info = {} for name, methods in methods.iteritems(): method_args = dict() for method in methods: if method[0][0] == "_": continue try: xml_docstring = et.fromstring(core.publish_doctree(method[1].im_func.func_doc).asdom().toxml()) arguments_block = ( xml_docstring.find("block_quote") .find("definition_list") .find("definition_list_item") .find("definition") .find("paragraph") .text ) except AttributeError, error: print error continue seperated_arguments = arguments_block.split("\n") arg = [] for item in seperated_arguments: items = re.findall(r"\s*([A-z0-9_]*)\s*\(([A-z0-9]*)\):" r"\s*(.*)", item) if len(items) > 0: if items[0][0] == "callback": continue arg.append(items[0]) if xml_docstring.find("paragraph") is not None: arg.append(("__description__", xml_docstring.find("paragraph").text)) method_args.update({method[0]: arg}) info.update({name: method_args})
def test_full_options(self): text = (".. blockdiag::\n" " :alt: hello world\n" " :align: center\n" " :desctable:\n" " :width: 200\n" " :height: 100\n" " :scale: 50%\n" " :name: foo\n" " :class: bar\n" " :figwidth: 400\n" " :figclass: baz\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(blockdiag_node, type(doctree[0])) self.assertEqual('A -> B', doctree[0]['code']) self.assertEqual('hello world', doctree[0]['alt']) self.assertEqual('center', doctree[0]['options']['align']) self.assertEqual(None, doctree[0]['options']['desctable']) self.assertEqual('200', doctree[0]['options']['width']) self.assertEqual('100', doctree[0]['options']['height']) self.assertEqual(50, doctree[0]['options']['scale']) self.assertEqual('hello world', doctree[0]['options']['alt']) self.assertEqual('foo', doctree[0]['options']['name']) self.assertEqual(['bar'], doctree[0]['options']['classes']) self.assertEqual('400px', doctree[0]['options']['figwidth']) self.assertEqual(['baz'], doctree[0]['options']['figclass'])
def __call__(self, data, contenttype=None, arguments=None): text = decode_data(data, contenttype) input = normalize_split_text(text) parser = MoinDirectives() while True: input = u'\n'.join(input) try: docutils_tree = core.publish_doctree(source=input) except utils.SystemMessage as inst: string_numb = re.match(re.compile(r'<string>:([0-9]*):\s*\(.*?\)\s*(.*)', re.X | re.U | re.M | re.S), str(inst)) if string_numb: str_num = string_numb.group(1) input = input.split('\n') if str_num: input = [('.. error::\n' ' ::\n' '\n' ' Parse error on line number {0}:\n' '\n' ' {1}\n' '\n' ' Go back and try to fix that.\n' '\n').format(str_num, string_numb.group(2).replace('\n', '\n '))] continue else: input = ['.. error::\n ::\n\n {0}\n\n'.format(str(inst).replace('\n', '\n '))] raise inst break visitor = NodeVisitor() walkabout(docutils_tree, visitor) return visitor.tree()
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_classes in _filter_resources(prefix, self.path(), self.statuses()): for resource_class in resource_classes: self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, "%s") self.props_schemata = properties.schemata(self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata(self.resource_class.attributes_schema) # NOTE(prazumovsky): Adding base_attributes_schema dict to # Resource class should means adding new attributes from this # dict to documentation of each resource, else there is no # chance to learn about base attributes. self.attrs_schemata.update(self.resource_class.base_attributes_schema) self.update_policy_schemata = properties.schemata(self.resource_class.update_policy_schema) self._status_str(resource_class.support_status, section) cls_doc = pydoc.getdoc(resource_class) if cls_doc: # allow for rst in the class comments cls_nodes = core.publish_doctree(cls_doc).children section.extend(cls_nodes) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_update_policy(section) self.contribute_hot_syntax(section) return content
def test_figclass_option(self): directives.setup(format="SVG", outputdir=self.tmpdir) text = ".. actdiag::\n" " :caption: hello world\n" " :figclass: baz\n" "\n" " A -> B" doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.figure, type(doctree[0])) self.assertEqual(["baz"], doctree[0]["classes"])
def test_figwidth_option2(self): directives.setup(format="SVG", outputdir=self.tmpdir) text = ".. actdiag::\n" " :caption: hello world\n" " :figwidth: image\n" "\n" " A -> B" doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.figure, type(doctree[0])) self.assertEqual("256px", doctree[0]["width"])
def test_desctable(self): directives.setup(format="SVG", outputdir=self.tmpdir) text = ".. actdiag::\n" " :desctable:\n" "\n" " A [description = foo]" " B [description = bar]" doctree = publish_doctree(text) self.assertEqual(2, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(nodes.table, type(doctree[1])) # tgroup self.assertEqual(4, len(doctree[1][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][1])) self.assertEqual(nodes.thead, type(doctree[1][0][2])) self.assertEqual(nodes.tbody, type(doctree[1][0][3])) # colspec self.assertEqual(50, doctree[1][0][0]["colwidth"]) self.assertEqual(50, doctree[1][0][1]["colwidth"]) # thead thead = doctree[1][0][2] self.assertEqual(2, len(thead[0])) self.assertEqual("Name", thead[0][0][0][0]) self.assertEqual("Description", thead[0][1][0][0]) # tbody tbody = doctree[1][0][3] self.assertEqual(2, len(tbody)) self.assertEqual("A", tbody[0][0][0][0]) self.assertEqual("foo", tbody[0][1][0][0]) self.assertEqual("B", tbody[1][0][0][0]) self.assertEqual("bar", tbody[1][1][0][0])
def test_desctable_option_with_numbered(self): directives.setup(format="SVG", outputdir=self.tmpdir) text = ".. actdiag::\n" " :desctable:\n" "\n" " A [numbered = 2]" " B [numbered = 1]" doctree = publish_doctree(text) self.assertEqual(2, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(nodes.table, type(doctree[1])) # tgroup self.assertEqual(4, len(doctree[1][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][1])) self.assertEqual(nodes.thead, type(doctree[1][0][2])) self.assertEqual(nodes.tbody, type(doctree[1][0][3])) # colspec self.assertEqual(25, doctree[1][0][0]["colwidth"]) self.assertEqual(50, doctree[1][0][1]["colwidth"]) # thead thead = doctree[1][0][2] self.assertEqual(2, len(thead[0])) self.assertEqual("No", thead[0][0][0][0]) self.assertEqual("Name", thead[0][1][0][0]) # tbody tbody = doctree[1][0][3] self.assertEqual(2, len(tbody)) self.assertEqual("1", tbody[0][0][0][0]) self.assertEqual("B", tbody[0][1][0][0]) self.assertEqual("2", tbody[1][0][0][0]) self.assertEqual("A", tbody[1][1][0][0])
def test_both_block_and_filename(self): text = (".. blockdiag:: unknown.diag\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.system_message, type(doctree[0]))
def test_call_without_braces(self): directives.setup(format="SVG", outputdir=self.tmpdir) text = ".. actdiag::\n" "\n" " A -> B" doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(0, doctree[0]["uri"].index(self.tmpdir))
def test_changelog(self): """Check version entry in changelog""" version = self.get_connector_version() if version[3]: version_text = self.get_connector_version_text(suffix=True) else: version_text = self.get_connector_version_text() found = False line = None with open('CHANGES.txt', 'r') as log: doctree = publish_doctree(log.read()).asdom() log.seek(0) for line in log.readlines(): if version_text in line: found = True break self.assertTrue(found, "Version {0} not found in CHANGES.txt".format( version_text )) re_version_title = re.compile(r'^v\d+\.\d+.\d+') releases = [] for title in doctree.getElementsByTagName('title'): title_text = title.childNodes[0].nodeValue match = re_version_title.match(title_text) if match: # Change Log entries can only be list items for item in title.nextSibling.childNodes: self.assertEqual(item.nodeName, 'list_item', "Change log entries must be list items")
def test_setup_inline_svg_is_false(self): directives.setup(format="SVG", outputdir=self.tmpdir, inline_svg=False) text = ".. actdiag::\n" "\n" " A -> B" doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(1, len(os.listdir(self.tmpdir)))
def view_pdf(name=None): """render a pdf file based on the given page .. note:: this is a bottle view Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) MANDATORY """ if name is None: return view_meta_index() files = glob.glob("{0}.rst".format(name)) if len(files) > 0: file_handle = open(files[0], 'r') dest_filename = name + '.pdf' doctree = publish_doctree(file_handle.read()) try: produce_pdf(doctree_content=doctree, filename=dest_filename) except: raise else: return static_file(dest_filename, root='', download=True) else: return abort(404)
def htmlize(params): "Parse text as RST and convert it to HTML" file = params.file if not file.rel_path.endswith(".rst"): return contents = file.contents settings = { # cloak email addresses to reduce spam 'cloak_email_addresses': 1, # Emit headers as H2, because H1 is already used 'doctitle_xform': False, 'strip_comments': 'true', #'dump_pseudo_xml': 'true', #'dump_settings': 'true', #'dump_transforms': 'true', # TODO: language_code? } # http://docutils.sourceforge.net/docs/dev/hacking.html # /usr/share/doc/python-docutils/ document = core.publish_doctree( source_path=params.file.rel_path, source=contents, settings_overrides=settings) return core.publish_from_doctree(document, writer=WebWriter(), writer_name='html', destination_path=params.file.rel_path, settings_overrides=settings)
def test_publish_pickle(self): # Test publishing a document tree with pickling and unpickling. # Produce the document tree. doctree = core.publish_doctree( source=test_document, reader_name="standalone", parser_name="restructuredtext", settings_spec=self ) self.assertTrue(isinstance(doctree, nodes.document)) # Pickle the document. Note: if this fails, some unpickleable # reference has been added somewhere within the document tree. # If so, you need to fix that. # # Note: Please do not remove this test, this is an important # requirement, applications will be built on the assumption # that we can pickle the document. # Remove the reporter and the transformer before pickling. doctree.reporter = None doctree.transformer = None doctree_pickled = pickle.dumps(doctree) self.assertTrue(isinstance(doctree_pickled, bytes)) del doctree # Unpickle the document. doctree_zombie = pickle.loads(doctree_pickled) self.assertTrue(isinstance(doctree_zombie, nodes.document)) # Write out the document: output = core.publish_from_doctree(doctree_zombie, writer_name="pseudoxml", settings_spec=self) self.assertEqual(output, pseudoxml_output)
def get_items_from_api_doc(): from sphinx.ext.autosummary import Autosummary from docutils.core import publish_doctree from docutils.parsers.rst import directives import docutils.nodes def add_item(item, api_doc_items): item = item.astext().strip().split() if len(item) > 0: # if item comes from a hand written table (like the Exploring section of Axis in api.rst) # we select the text from the left column if isinstance(item, list): item = item[0] api_doc_items.append(item) api_doc_items = [] directives.register_directive('autosummary', Autosummary) cleanup_line = lambda line: line.replace(':attr:', ' ').replace('`', ' ') check_line = lambda line: len(line) and not (line.startswith('..') or ':' in line) with open('./api.rst', mode='r') as f: content = [cleanup_line(line) for line in f.readlines()] content = '\n'.join([line for line in content if check_line(line)]) document = publish_doctree(content) nodes = list(document) for node in nodes: if isinstance(node, docutils.nodes.block_quote): for item in node.children: add_item(item, api_doc_items) if isinstance(node, docutils.nodes.table): for item in node[0][2].children: add_item(item, api_doc_items) return api_doc_items
def run(self): """Run listing directive.""" _fname = self.arguments.pop(0) fname = _fname.replace('/', os.sep) try: lang = self.arguments.pop(0) self.options['code'] = lang except IndexError: self.options['literal'] = True if len(self.folders) == 1: listings_folder = next(iter(self.folders.keys())) if fname.startswith(listings_folder): fpath = os.path.join(fname) # new syntax: specify folder name else: fpath = os.path.join(listings_folder, fname) # old syntax: don't specify folder name else: fpath = os.path.join(fname) # must be new syntax: specify folder name self.arguments.insert(0, fpath) if 'linenos' in self.options: self.options['number-lines'] = self.options['linenos'] with io.open(fpath, 'r+', encoding='utf8') as fileobject: self.content = fileobject.read().splitlines() self.state.document.settings.record_dependencies.add(fpath) target = urlunsplit(("link", 'listing', fpath.replace('\\', '/'), '', '')) src_target = urlunsplit(("link", 'listing_source', fpath.replace('\\', '/'), '', '')) src_label = self.site.MESSAGES('Source') generated_nodes = ( [core.publish_doctree('`{0} <{1}>`_ `({2}) <{3}>`_' .format( _fname, target, src_label, src_target))[0]]) generated_nodes += self.get_code_from_file(fileobject) return generated_nodes
def test_desctable_option_using_node_group(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. blockdiag::\n" " :desctable:\n" "\n" " A [description = foo]" " B [description = bar]" " group { A }") doctree = publish_doctree(text) self.assertEqual(2, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(nodes.table, type(doctree[1])) self.assertEqual(1, len(doctree[1])) self.assertEqual(nodes.tgroup, type(doctree[1][0])) # tgroup self.assertEqual(4, len(doctree[1][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][0])) self.assertEqual(nodes.colspec, type(doctree[1][0][1])) self.assertEqual(nodes.thead, type(doctree[1][0][2])) self.assertEqual(nodes.tbody, type(doctree[1][0][3])) # colspec self.assertEqual(0, len(doctree[1][0][0])) self.assertEqual(50, doctree[1][0][0]['colwidth']) self.assertEqual(0, len(doctree[1][0][1])) self.assertEqual(50, doctree[1][0][1]['colwidth']) # thead thead = doctree[1][0][2] self.assertEqual(1, len(thead)) self.assertEqual(2, len(thead[0])) self.assertEqual(1, len(thead[0][0])) self.assertEqual(1, len(thead[0][0][0])) self.assertEqual('Name', thead[0][0][0][0]) self.assertEqual(1, len(thead[0][1])) self.assertEqual(1, len(thead[0][1][0])) self.assertEqual('Description', thead[0][1][0][0]) # tbody tbody = doctree[1][0][3] self.assertEqual(2, len(tbody)) self.assertEqual(2, len(tbody[0])) self.assertEqual(1, len(tbody[0][0])) self.assertEqual(1, len(tbody[0][0][0])) self.assertEqual('A', tbody[0][0][0][0]) self.assertEqual(1, len(tbody[0][1])) self.assertEqual('foo', tbody[0][1][0][0]) self.assertEqual(2, len(tbody[1])) self.assertEqual(1, len(tbody[1][0])) self.assertEqual(1, len(tbody[1][0][0])) self.assertEqual('B', tbody[1][0][0][0]) self.assertEqual(1, len(tbody[1][1])) self.assertEqual('bar', tbody[1][1][0][0])
def run(self): prefix = self.arguments and self.arguments.pop() or None content = [] for resource_type, resource_classes in _filter_resources( prefix, self.path(), self.statuses()): for resource_class in resource_classes: self.resource_type = resource_type self.resource_class = resource_class section = self._section(content, resource_type, '%s') self.props_schemata = properties.schemata( self.resource_class.properties_schema) self.attrs_schemata = attributes.schemata( self.resource_class.attributes_schema) self._status_str(resource_class.support_status, section) cls_doc = pydoc.getdoc(resource_class) if cls_doc: # allow for rst in the class comments cls_nodes = core.publish_doctree(cls_doc).children section.extend(cls_nodes) self.contribute_properties(section) self.contribute_attributes(section) self.contribute_hot_syntax(section) self.contribute_yaml_syntax(section) self.contribute_json_syntax(section) return content
def test_pickle(self): doctree = core.publish_doctree( source='Title\n=====\n\nparagraph\n', settings_overrides={'_disable_config': 1}) dill = pickle.dumps(doctree) reconstituted = pickle.loads(dill) self.assertEquals(doctree.pformat(), reconstituted.pformat())
def test_setup_nodoctype_is_true(self): directives.setup(format='SVG', outputdir=self.tmpdir, nodoctype=True) text = (".. rackdiag::\n" "\n" " 1: server\n" " 2: database\n") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[-1])) svg = open(doctree[0]['uri']).read() self.assertNotEqual( "<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE ", svg[:49])
def setUp(self): source = join(dirname(__file__), 'doc', 'doctree.rst') with open(source, 'r', encoding='utf-8') as rst: self.doctree = publish_doctree(rst.read()) self.node = self.doctree.next_node(self._matches_node_i) self.node_addresses = [ (nodes.section(), ()), (nodes.paragraph(), ()), (nodes.comment(), ()), (nodes.Text('text'), ())]
def get_field_list(source): dom = publish_doctree(source).asdom() tree = fromstring(dom.toxml()) for field in tree.iter(): if field.tag == 'field': name = next(field.iter(tag='field_name')) body = next(field.iter(tag='field_body')) yield name.text.lower(), ''.join(body.itertext()) elif field.tag in ('author', 'date'): yield field.tag, ''.join(field.itertext())
def test_setup_noviewbox_is_false(self): directives.setup(format='SVG', outputdir=self.tmpdir, noviewbox=False) text = (".. seqdiag::\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) svg = open(doctree[0]['uri']).read() self.assertRegexpMatches(svg, '<svg viewBox="0 0 \d+ \d+" ')
def test_align_option4(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" " :align: unknown\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.system_message, type(doctree[0])) # clear stderr outputs (ignore ERROR) from io import StringIO sys.stderr = StringIO()
def test_setup_nodoctype_is_false(self): directives.setup(format='SVG', outputdir=self.tmpdir, nodoctype=False) text = (".. seqdiag::\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) svg = open(doctree[0]['uri']).read() self.assertEqual( "<?xml version='1.0' encoding='UTF-8'?>\n" "<!DOCTYPE ", svg[:49])
def test_emphasis(self): input = """ *emphasis*""" doctree = publish_doctree(input) elements = self.converter.gen_elements(doctree, 0) self.assertEqual(len(elements), 1) para = elements[0] self.assertEqual(para.text, '<i>emphasis</i>') parafrag = para.frags[0] self.assertEqual(parafrag.italic, 1)
def test_setup_inline_svg_is_false(self): directives.setup(format='SVG', outputdir=self.tmpdir, inline_svg=False) text = (".. rackdiag::\n" "\n" " 1: server\n" " 2: database\n") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(1, len(os.listdir(self.tmpdir)))
def _publish(source): """ Parse rst source string into doctree. """ doctree = publish_doctree( source=source, reader=NoDocInfoReader(), parser_name='restructuredtext', ) return doctree
def test_call_without_braces(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. rackdiag::\n" "\n" " 1: server\n" " 2: database\n") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_setup_nodoctype_is_true(self): directives.setup(format='SVG', outputdir=self.tmpdir, nodoctype=True) text = (".. seqdiag::\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[-1])) svg = open(doctree[0]['uri']).read() self.assertEqual("<svg viewBox=\"0 0 ", svg[:18])
def test_strong(self): input = """ **strong**""" doctree = publish_doctree(input) elements = self.converter.gen_elements(doctree, 0) self.assertEqual(len(elements), 1) para = elements[0] self.assertEqual(para.text, '<b>strong</b>') parafrag = para.frags[0] self.assertEqual(parafrag.bold, 1)
def parse(app, docname, text): app.env.temp_data['docname'] = docname return publish_doctree(text, app.srcdir / docname + '.rst', reader=SphinxStandaloneReader(app), parser=RSTParser(), settings_overrides={ 'env': app.env, 'gettext_compact': True })
def extract_signature(docstring): """Extract the signature from a docstring. :sig: (str) -> Optional[str] :param docstring: Docstring to extract the signature from. :return: Extracted signature, or ``None`` if there's no signature. """ root = publish_doctree(docstring, settings_overrides={"report_level": 5}) fields = get_fields(root) return fields.get(SIG_FIELD)
def _parse_doc(func): """Extract documentation from a function's docstring.""" doc = inspect.getdoc(func) if doc is None: return _Doc('', {}) # Convert Google- or Numpy-style docstrings to RST. # (Should do nothing if not in either style.) doc = str(GoogleDocstring(doc)) doc = str(NumpyDocstring(doc)) dom = publish_doctree(doc).asdom() etree = ElementTree.fromstring(dom.toxml()) doctext = [] for element in etree: if element.tag == 'paragraph': doctext.append(_get_text(element)) elif element.tag == 'literal_block': doctext.append(_indent(_get_text(element))) doctext = '\n\n'.join(doctext) fields = etree.findall('.//field') params = defaultdict(dict) for field in fields: field_name = field.find('field_name') field_body = field.find('field_body') parts = field_name.text.split() if len(parts) == 2: doctype, name = parts elif len(parts) == 3: doctype, type_, name = parts if doctype not in _PARAM_TYPES: log.debug('ignoring field %s', field_name.text) continue log.debug('inline param type %s', type_) if 'type' in params[name]: raise ValueError('type defined twice for {}'.format(name)) params[name]['type'] = type_ else: log.debug('ignoring field %s', field_name.text) continue if doctype in _PARAM_TYPES: doctype = 'param' if doctype in _TYPE_NAMES: doctype = 'type' text = _get_text(field_body) log.debug('%s %s: %s', doctype, name, text) if doctype in params[name]: raise ValueError('{} defined twice for {}'.format(doctype, name)) params[name][doctype] = text tuples = {} for name, values in params.items(): tuples[name] = _Param(values.get('param'), values.get('type')) return _Doc(doctext, tuples)
def test_align_option3(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" " :align: right\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual('right', doctree[0]['align']) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_height_option(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" " :height: 100\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual('100', doctree[0]['height']) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_scale_option(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" " :scale: 50%\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(50, doctree[0]['scale']) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_class_option(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" " :class: bar%\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(['bar'], doctree[0]['classes']) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_existing_file(self): input=""" This one exists: .. code-block:: py :include: %s """ % input_file_path('test_include.py') doctree=publish_doctree(input) include = doctree.children[1] self.assertEqual(include.tagname, 'literal_block') self.assertEqual(include.children[0].astext(), u'# -*- coding: utf-8 -*-')
def test_setup_inline_svg_is_true_but_nonsvg_format(self): directives.setup(format='PNG', outputdir=self.tmpdir, inline_svg=True) text = (".. nwdiag::\n" "\n" " network {" " A" " B" " }") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0]))
def test_setup_inline_svg_is_true_with_multibytes(self): directives.setup(format='SVG', outputdir=self.tmpdir, inline_svg=True) text = (".. nwdiag::\n" "\n" " network {" " あ" " い" " }") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.raw, type(doctree[0]))
def test_setup_noviewbox_is_true(self): directives.setup(format='SVG', outputdir=self.tmpdir, noviewbox=True) text = (".. packetdiag::\n" "\n" " 1: server\n" " 2: database\n") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) svg = open(doctree[0]['uri']).read() self.assertRegexpMatches(svg, r'<svg height="\d+" width="\d+" ')
def test_figclass_option(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. blockdiag::\n" " :caption: hello world\n" " :figclass: baz\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.figure, type(doctree[0])) self.assertEqual(['baz'], doctree[0]['classes'])
def test_figwidth_option2(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. blockdiag::\n" " :caption: hello world\n" " :figwidth: image\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.figure, type(doctree[0])) self.assertEqual('448px', doctree[0]['width'])
def test_desctable_option_without_description(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. rackdiag::\n" " :desctable:\n" "\n" " 1: server\n" " 2: database\n") doctree = publish_doctree(text) self.assertEqual(2, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(nodes.table, type(doctree[1]))
def test_call_with_brace(self): directives.setup(format='SVG', outputdir=self.tmpdir) text = (".. seqdiag::\n" "\n" " {" " A -> B" " }") doctree = publish_doctree(text) self.assertEqual(1, len(doctree)) self.assertEqual(nodes.image, type(doctree[0])) self.assertEqual(0, doctree[0]['uri'].index(self.tmpdir))
def test_maxwidth_option(self): text = (".. blockdiag::\n" " :maxwidth: 200\n" "\n" " A -> B") doctree = publish_doctree(text) self.assertEqual(2, len(doctree)) self.assertEqual(blockdiag_node, type(doctree[0])) self.assertEqual('A -> B', doctree[0]['code']) self.assertEqual('200', doctree[0]['options']['width']) self.assertEqual(nodes.system_message, type(doctree[1]))
def test_wrong_lang(self): input=""" This one exists: .. code-block:: nothing :include: %s """ % input_file_path('test_include.py') doctree=publish_doctree(input) include = doctree.children[1] self.assertEqual(include.tagname, 'literal_block') self.assertEqual(include.astext().split('\n')[0], u'# -*- coding: utf-8 -*-')
def _latest_version(self): contents = self._read(self.change_file) doctree = etree.fromstring((publish_doctree(contents).asdom()).toxml()) titles = [ title for section in doctree.findall('section') for title in section.findall('title') ] versions = [title.text for title in titles] or [ subtitle.text for subtitle in doctree.findall('subtitle') ] return versions[0] if versions else ''