从pytest中创建并运行markdown readme

pytest2md的Python项目详细描述



作者:GK 版本:190427


生成降价-同时测试包含的声明

构建状态codecovpypi version src=

目录

没有什么事情比那些不按宣布的方式工作的事情更烦人了, 尤其是当你在投入时间和精力之后才发现的时候。

文档通常容易产生这种情况,因为很难保存 100%与代码演进同步。

这是一组工具,生成文档,同时验证文档 关于代码行为的声明-无需修改源代码,例如通过修改 文档字符串:

 src=

< Buff行情>

当文档使用大量代码示例时 如图所示编写它的额外好处是可以使用源代码 代码自动格式化程序

其他示例:

这个"readme.md"内置在这个模板中, 其中HTML注释样式占位符 在这个测试文件上运行pytest时被替换:

"""Creates Readme - while testing functions of p2m.While pytest is running we simply assemble from scratch an intermediate .md filein append only mode, located within the tests folder.This we insert between two seperators in the target markdown file, as the lasttest function, done."""importpytest2mdasp2mimportpytest,json,os,timefromfunctoolsimportpartialfromuuidimportuuid4importjson# a P2M instance contains all we need:p2m=p2m.P2M(__file__,fn_target_md='README.md')# py2.7 compat:# parametrizing the shell run results:run=partial(p2m.bash_run,no_cmd_path=True)classTestChapter1:deftest_one(self):t="""        This is a set of tools, *generating* documentation, while verifying the documented        claims about code behaviour - without the need to adapt the source code, e.g. by modifying        doc strings:        ![](./assets/shot1.png)        > When the documentation is using a lot of code examples then a very welcome        additional benefit of writing it like shown is the availability of [source        code autoformatters](https://github.com/ambv/black).        Other Example:        This "README.md" was built into [this](./.README.tmpl.md) template,        where [title:html comment style placeholders,fmatch:.README.tmpl.md,show_raw:True]<SRC>        had been replaced while running pytest on this testfile:        <from_file: %s>        """%(__file__,)p2m.md(t)p2m.md("""        Lets run a bash command and assert on its results.        Note that the command is shown in the readme, incl. result and the result        can be asserted upon.        """)res=run('cat "/etc/hosts" | grep localhost')assert'127.0.0.1'inres[0]['res']deftest_two(self):res=run(['ls "%(d_test)s"'%p2m.ctx,'ls -lta /etc/hosts'])assert'tutorial'inres[0]['res']assert'hosts'inres[1]['res']deftest_simple_pyfuncs(self):"""        # Inline Python Function Execution        via the `md_from_source_code` function you can write fluent markdown        (tested) python combos:        """deffoo():hi='hello world'assert'world'inhiprint(hi.replace('world','joe'))"""        The functions are evaluated and documented in the order they show up        within the textblocks.        > Please keep tripple apostrophes - we split the text blocks,        searching for those.        State is kept within the outer pytest function, like normally in python.        I.e. if you require new state, then start a new pytest function.        Stdout is redirected to an output collector function, i.e. if you print        this does result in an "Output" block. If the printout starts with        "MARKDOWN:" then we won't wrap that output into fenced code blocks but        display as is.        > If the string 'breakpoint' occurs in a function body, we won't redirect        standardout for displaying output.        # Tools        Also there are few tools available, e.g this one:        """defmdtable():ht=p2m.html_tablet=ht([['joe','doe'],['suzie','wong']],['first','last'],summary='names. click to open...',)assert'details'intassert'joe</td'intprint(t)"""        Another tool is the simple TOC generator, invoked like at the end of this file.        """p2m.md_from_source_code()deftest_file_create_show(self):p2m.md("""        # Files        When working with files, the `sh_file` function is helpful,        producing output like this one:""")ts=time.ctime()c=json.dumps({'a':[{'testfile':'created'},'at',ts]},indent=4)# if content is given it will create it:fn='/tmp/'+str(uuid4())p2m.sh_file(fn,lang='javascript',content=c)# check existance:withopen(fn)asfd:assertfd.read()==cos.unlink(fn)deftest_mdtool(self):md="""        # Link Replacements        Technical markdown content wants to link to source code often.        How to get those links working and that convenient?        The module does offer also some source finding / link replacement feature,        via the [mdtool]<SRC> module. The latter link was built simply by this:        ```        [mdtool]<SRC>        ```        Other example: This [pytest2md]<SRC> link was created by replacing "SRC" with the path        to a file matching, under a given directory, prefixed by an arbitrary base URL.        ## Spec        These will be replaced:        `[title:this,fmatch:test_tutorial,lmatch:exotic] <SRC>` (remove space between] and <)        - title: The link title - text the user reads        - fmatch: substring match for the link destination file        - lmatch: Find matching line within that file        - show_raw: Link to raw version of file, not the one rendered by the          repo server        - path: Fix file path (usually derived by fmach)        - line: Fix the line number of the link (usually done via lmatch)        ## Code Repo Hoster Specific Source Links        Github, Gitlab, Bitbucked or Plain directory based static content servers        all have their conventional URLs regarding those links.        Since all of these are just serving static content w/o js possibilities,        you have to parametrize the intended hoster in your environment, before        running a pytest / push cycle. That way the links will be working on the hoster.        Currently we understand the following namespaces for links:        ```javascript        _link_names_        ```        ### Setting a link template        - `export MD_LINKS_FOR=github   ` # before running pytest / push        - `<!-- md_links_for: github -->` # in the markdown template, static        The latter can be overwritten by environ, should you want to push from time to time        to a different code hoster.        ### Link Refs        We minimize the problem of varying generated target markdown, dependent on the hoster.        How? Like [any problem in IT is solved](https://en.wikipedia.org/wiki/Fundamental_theorem_of_software_engineering).        By building [reference links](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#links)        the differences of e.g. a README.md for github vs. gitlab is        restricted to the links section on the end of the generated markdown.        In the markdown bodies you'll just see link names, which remain the same.        > Check the end of the [title:rendering result,fmatch:README.md,show_raw:True]<SRC> at the end of this README.md,        in order to see the results for the hoster you are reading this markdown file currently.        ## Summary        - At normal runs of pytest, the link base URL is just a local `file://` link,        - Before pushes one can set via environ (e.g. `export          MD_LINKS_FOR=github`)  these e.g. to the github base URL or the repo.        - `[key-values]` constructs are supported as well, extending to beyond          just the base url. Example following:        """.replace('_link_names_',json.dumps(p2m.src_link_templates,indent=4,sort_keys=2),)p2m.md(md)deftest_sh_code(self):p2m.md('Source code showing is done like this:')p2m.sh_code(self.test_sh_code)p2m.md('> Is [title:this,fmatch:test_tutorial,lmatch:exotic]<SRC> an exotic form of a recursion? ;-)  ')deftest_write(self):"""has to be the last 'test'"""# default is ../README.mdp2m.write_markdown(with_source_ref=True,make_toc=True)

让我们运行bash命令并对其结果进行断言。 注意,该命令显示在自述文件中,包括result和result 可以断言。

$ cat "/etc/hosts"| grep localhost
# localhost is used to configure the loopback interface127.0.0.1  localhost lo sd1 sd3 sa1 sa2 sb1 sb2
::1             localhost
$ ls "/Users/gk/GitHub/pytest2md/tests"
__pycache__
test_basics.py
test_changelog.py
test_tutorial.py

$ ls -lta /etc/hosts
-rw-r--r--  1 root  wheel  1047 Mar  111:35 /etc/hosts

内联python函数执行

通过md_from_source_code函数,您可以编写流畅的标记 (经过测试)python组合:

hi='hello world'assert'world'inhiprint(hi.replace('world','joe'))

输出:

hello joe

按照功能出现的顺序对其进行评估和记录 在文本块中。

< Buff行情>

请保留三个撇号-我们拆分文本块, 正在搜索这些。

状态保持在外部pytest函数中,就像通常在python中一样。 即,如果您需要新的状态,则启动一个新的pytest函数。

stdout被重定向到输出收集器函数,即如果您打印 这会导致"输出"块。如果打印开始于 "markdown:"然后我们不会将输出包装成有栅栏的代码块,但是 按原样显示。

< Buff行情>

如果字符串"breakpoint"出现在函数体中,则不会重定向 显示输出的标准输出。

工具

此外,几乎没有可用的工具,例如此工具:

ht=p2m.html_tablet=ht([['joe','doe'],['suzie','wong']],['first','last'],summary='names. click to open...',)assert'details'intassert'joe</td'intprint(t)
<细节><摘要>姓名。单击打开…<表>第一个最后一个 乔 苏西王<表><详细内容>

另一个工具是简单的toc生成器,类似于在文件末尾调用它。

文件

使用文件时,sh_file函数很有帮助, 产生这样的输出:

$cat"e06a64dc-6448-4f36-bf55-d69e852b6682"{"a":[{"testfile":"created"},"at","Mon Apr 22 13:39:16 2019"]}

链接替换

技术性降价内容通常希望链接到源代码。 如何让这些链接工作和方便?

该模块还提供了一些源代码查找/链接替换功能, 通过mdtool模块

[mdtool]<SRC>

其他示例:通过将"src"替换为路径创建链接。 与给定目录下的文件匹配,前缀为任意基URL。

规格

这些将被替换:

[标题:this,fmatch:test_tutorial,lmatch:otic]<;src>;(删除]和<;之间的空格)

  • title:链接标题-用户读取的文本
  • fmatch:链接目标文件的子字符串匹配
  • lmatch:在该文件中查找匹配行
  • show_raw:链接到文件的原始版本,而不是由 回购服务器
  • 路径:修复文件路径(通常由fmach派生)
  • line:固定链接的行号(通常通过lmatch完成)

代码回购主机特定的源链接

github、gitlab、基于位块或纯目录的静态内容服务器 所有人都有关于这些链接的常规URL。

因为所有这些都只是提供不带js可能性的静态内容, 你必须在你的环境中对预定的旅馆进行参数化 运行pytest/push循环。这样链接就可以在招待所工作。

目前我们了解以下链接的命名空间:

{"github":"https://github.com/%(gh_repo_name)s/blob/%(git_rev)s/%(path)s%(line:#L%s)s","github_raw":"https://raw.githubusercontent.com/%(gh_repo_name)s/%(git_rev)s/%(path)s%(line:#L%s)s","static":"file://%(d_repo_base)s/%(path)s","static_raw":"file://%(d_repo_base)s/%(path)s"}

设置链接模板
  • 在运行pytest/push之前导出md\u links\u for=github
  • <;!--md_links_for:github-->;在降价模板中,静态

如果您想不时地推送,后者可以被environ覆盖 到另一个代码宿主。

链接参考

我们最小化的问题,变化生成的目标降价,取决于招待。 怎样?就像软件工程的基本定理rel="nofollow">中的任何问题都会得到解决

通过建立参考链接 github的readme.md与gitlab的区别在于 仅限于生成的标记末尾的"链接"部分。 在标记体中,您只会看到链接名称,它们保持不变。

< Buff行情>

检查呈现结果,在这个readme.md的末尾, 为了查看招待所的结果,您当前正在读取此降价文件。

摘要

  • 在pytest的正常运行中,链接基url只是一个本地文件://链接,

  • 在推送之前,可以通过environ(例如export md_links\u for=github)设置这些链接,例如到github基url或repo。

  • [键值]还支持构造,扩展到beyond 只是基本URL。示例如下:

源代码显示如下:

"""Creates Readme - while testing functions of p2m.While pytest is running we simply assemble from scratch an intermediate .md filein append only mode, located within the tests folder.This we insert between two seperators in the target markdown file, as the lasttest function, done."""importpytest2mdasp2mimportpytest,json,os,timefromfunctoolsimportpartialfromuuidimportuuid4importjson# a P2M instance contains all we need:p2m=p2m.P2M(__file__,fn_target_md='README.md')# py2.7 compat:# parametrizing the shell run results:run=partial(p2m.bash_run,no_cmd_path=True)classTestChapter1:deftest_one(self):t="""        This is a set of tools, *generating* documentation, while verifying the documented        claims about code behaviour - without the need to adapt the source code, e.g. by modifying        doc strings:        ![](./assets/shot1.png)        > When the documentation is using a lot of code examples then a very welcome        additional benefit of writing it like shown is the availability of [source        code autoformatters](https://github.com/ambv/black).        Other Example:        This "README.md" was built into [this](./.README.tmpl.md) template,        where [title:html comment style placeholders,fmatch:.README.tmpl.md,show_raw:True]<SRC>        had been replaced while running pytest on this testfile:        <from_file: %s>        """%(__file__,)p2m.md(t)p2m.md("""        Lets run a bash command and assert on its results.        Note that the command is shown in the readme, incl. result and the result        can be asserted upon.        """)res=run('cat "/etc/hosts" | grep localhost')assert'127.0.0.1'inres[0]['res']deftest_two(self):res=run(['ls "%(d_test)s"'%p2m.ctx,'ls -lta /etc/hosts'])assert'tutorial'inres[0]['res']assert'hosts'inres[1]['res']deftest_simple_pyfuncs(self):"""        # Inline Python Function Execution        via the `md_from_source_code` function you can write fluent markdown        (tested) python combos:        """deffoo():hi='hello world'assert'world'inhiprint(hi.replace('world','joe'))"""        The functions are evaluated and documented in the order they show up        within the textblocks.        > Please keep tripple apostrophes - we split the text blocks,        searching for those.        State is kept within the outer pytest function, like normally in python.        I.e. if you require new state, then start a new pytest function.        Stdout is redirected to an output collector function, i.e. if you print        this does result in an "Output" block. If the printout starts with        "MARKDOWN:" then we won't wrap that output into fenced code blocks but        display as is.        > If the string 'breakpoint' occurs in a function body, we won't redirect        standardout for displaying output.        # Tools        Also there are few tools available, e.g this one:        """defmdtable():ht=p2m.html_tablet=ht([['joe','doe'],['suzie','wong']],['first','last'],summary='names. click to open...',)assert'details'intassert'joe</td'intprint(t)"""        Another tool is the simple TOC generator, invoked like at the end of this file.        """p2m.md_from_source_code()deftest_file_create_show(self):p2m.md("""        # Files        When working with files, the `sh_file` function is helpful,        producing output like this one:""")ts=time.ctime()c=json.dumps({'a':[{'testfile':'created'},'at',ts]},indent=4)# if content is given it will create it:fn='/tmp/'+str(uuid4())p2m.sh_file(fn,lang='javascript',content=c)# check existance:withopen(fn)asfd:assertfd.read()==cos.unlink(fn)deftest_mdtool(self):md="""        # Link Replacements        Technical markdown content wants to link to source code often.        How to get those links working and that convenient?        The module does offer also some source finding / link replacement feature,        via the [mdtool]<SRC> module. The latter link was built simply by this:        ```        [mdtool]<SRC>        ```        Other example: This [pytest2md]<SRC> link was created by replacing "SRC" with the path        to a file matching, under a given directory, prefixed by an arbitrary base URL.        ## Spec        These will be replaced:        `[title:this,fmatch:test_tutorial,lmatch:exotic] <SRC>` (remove space between] and <)        - title: The link title - text the user reads        - fmatch: substring match for the link destination file        - lmatch: Find matching line within that file        - show_raw: Link to raw version of file, not the one rendered by the          repo server        - path: Fix file path (usually derived by fmach)        - line: Fix the line number of the link (usually done via lmatch)        ## Code Repo Hoster Specific Source Links        Github, Gitlab, Bitbucked or Plain directory based static content servers        all have their conventional URLs regarding those links.        Since all of these are just serving static content w/o js possibilities,        you have to parametrize the intended hoster in your environment, before        running a pytest / push cycle. That way the links will be working on the hoster.        Currently we understand the following namespaces for links:        ```javascript        _link_names_        ```        ### Setting a link template        - `export MD_LINKS_FOR=github   ` # before running pytest / push        - `<!-- md_links_for: github -->` # in the markdown template, static        The latter can be overwritten by environ, should you want to push from time to time        to a different code hoster.        ### Link Refs        We minimize the problem of varying generated target markdown, dependent on the hoster.        How? Like [any problem in IT is solved](https://en.wikipedia.org/wiki/Fundamental_theorem_of_software_engineering).        By building [reference links](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#links)        the differences of e.g. a README.md for github vs. gitlab is        restricted to the links section on the end of the generated markdown.        In the markdown bodies you'll just see link names, which remain the same.        > Check the end of the [title:rendering result,fmatch:README.md,show_raw:True]<SRC> at the end of this README.md,        in order to see the results for the hoster you are reading this markdown file currently.        ## Summary        - At normal runs of pytest, the link base URL is just a local `file://` link,        - Before pushes one can set via environ (e.g. `export          MD_LINKS_FOR=github`)  these e.g. to the github base URL or the repo.        - `[key-values]` constructs are supported as well, extending to beyond          just the base url. Example following:        """.replace('_link_names_',json.dumps(p2m.src_link_templates,indent=4,sort_keys=2),)p2m.md(md)deftest_sh_code(self):p2m.md('Source code showing is done like this:')p2m.sh_code(self.test_sh_code)p2m.md('> Is [title:this,fmatch:test_tutorial,lmatch:exotic]<SRC> an exotic form of a recursion? ;-)  ')deftest_write(self):"""has to be the last 'test'"""# default is ../README.mdp2m.write_markdown(with_source_ref=True,make_toc=True)
0 < Buff行情>

这是不是一种奇特的递归形式?;(-)

由pytest2md自动生成,运行pytest2md

隔离

没有。如果你想让你的主机正常运行pytest,那么你将 运行降价生成测试时得到相同的结果。


这里是一个更大的教程,来自pytest2md

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java嵌套循环打印一个数字,旁边有相同数量的星号   java JodReports替代方案   java如何将模型类parcelable对象从片段传递到活动?   java JCS缓存删除功能不删除特定元素   如何打开。Java的dll文件。   java在这种情况下如何选择聚合根?   java从CellEditorListener获取编辑的TreeNode   Java到web服务和mysql   从openssl ec在Java中创建公钥时出现加密无效密钥异常   Java数组:添加多个数组的元素时忽略空数组   java在初始化后向fragment发送数据   JButtons的java数组正在返回void   若联接列不包含特定值,则java JPA条件生成器仅返回实体   java ActionBar问题:NPE   java Portlet是被广泛使用还是非常罕见?