├── .github └── workflows │ └── tests.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── dinosaur.py ├── icon.png ├── mktestdocs ├── __init__.py └── __main__.py ├── setup.py └── tests ├── __init__.py ├── conftest.py ├── data ├── bad │ ├── a.md │ ├── b.md │ └── big-bad.md └── good │ ├── a.md │ ├── b.md │ ├── big-good.md │ ├── c.md │ └── d.md ├── docs ├── additional-language-support.md ├── bash-support.md ├── multiple-code-blocks.md └── test.md ├── test_actual_docstrings.py ├── test_class.py ├── test_codeblock.py ├── test_format_docstring.py ├── test_markdown.py └── test_mktestdocs.py /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | strategy: 16 | matrix: 17 | python-version: [3.9, "3.10", "3.11", "3.12"] 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v2 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install --upgrade pip 28 | pip install pytest 29 | - name: Test with pytest 30 | run: | 31 | pytest 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | .vscode 131 | .idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | black: 2 | black mktestdocs tests setup.py 3 | 4 | test: 5 | pytest 6 | 7 | check: black test 8 | 9 | install: 10 | python -m pip install -e ".[test]" 11 | 12 | pypi: 13 | python setup.py sdist 14 | python setup.py bdist_wheel --universal 15 | twine upload dist/* 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### mktestdocs 4 | 5 | Run pytest against markdown files/docstrings. 6 | 7 | # Installation 8 | 9 | ``` 10 | pip install mktestdocs 11 | ``` 12 | 13 | ## Usage 14 | 15 | Let's say that you're using [mkdocs](https://squidfunk.github.io/mkdocs-material/getting-started/) 16 | for your documentation. Then you're writing down markdown to explain how your Python packages work. 17 | It'd be a shame if a codeblock had an error in it, so it'd be 18 | great if you could run your unit tests against them. 19 | 20 | This package allows you to do _just that_. Here's an example: 21 | 22 | ```python 23 | import pathlib 24 | import pytest 25 | 26 | from mktestdocs import check_md_file 27 | 28 | # Note the use of `str`, makes for pretty output 29 | @pytest.mark.parametrize('fpath', pathlib.Path("docs").glob("**/*.md"), ids=str) 30 | def test_files_good(fpath): 31 | check_md_file(fpath=fpath) 32 | ``` 33 | 34 | This will take any codeblock that starts with *\`\`\`python* and run it, checking 35 | for any errors that might happen. This means that if your docs contain asserts, that 36 | you get some unit-tests for free! 37 | 38 | ## Multiple Code Blocks 39 | 40 | Let's suppose that you have the following markdown file: 41 | 42 | This is a code block 43 | 44 | ```python 45 | from operator import add 46 | a = 1 47 | b = 2 48 | ``` 49 | 50 | This code-block should run fine. 51 | 52 | ```python 53 | assert add(1, 2) == 3 54 | ``` 55 | 56 | Then in this case the second code-block depends on the first code-block. The standard settings of `check_md_file` assume that each code-block needs to run independently. If you'd like to test markdown files with these sequential code-blocks be sure to set `memory=True`. 57 | 58 | ```python 59 | import pathlib 60 | 61 | from mktestdocs import check_md_file 62 | 63 | fpath = pathlib.Path("docs") / "multiple-code-blocks.md" 64 | 65 | try: 66 | # Assume that cell-blocks are independent. 67 | check_md_file(fpath=fpath) 68 | except NameError: 69 | # But they weren't 70 | pass 71 | 72 | # Assumes that cell-blocks depend on each other. 73 | check_md_file(fpath=fpath, memory=True) 74 | ``` 75 | 76 | ## Markdown in Docstrings 77 | 78 | You might also have docstrings written in markdown. Those can be easily checked 79 | as well. 80 | 81 | ```python 82 | # I'm assuming that we've got a library called dinosaur 83 | from dinosaur import roar, super_roar 84 | 85 | import pytest 86 | from mktestdocs import check_docstring 87 | 88 | # Note the use of `__name__`, makes for pretty output 89 | @pytest.mark.parametrize('func', [roar, super_roar], ids=lambda d: d.__name__) 90 | def test_docstring(func): 91 | check_docstring(obj=func) 92 | ``` 93 | 94 | There's even some utilities for grab all the docstrings from classes that you've defined. 95 | 96 | ```python 97 | # I'm assuming that we've got a library called dinosaur 98 | from dinosaur import Dinosaur 99 | 100 | import pytest 101 | from mktestdocs import check_docstring, get_codeblock_members 102 | 103 | # This retrieves all methods/properties that have a docstring. 104 | members = get_codeblock_members(Dinosaur) 105 | 106 | # Note the use of `__qualname__`, makes for pretty output 107 | @pytest.mark.parametrize("obj", members, ids=lambda d: d.__qualname__) 108 | def test_member(obj): 109 | check_docstring(obj) 110 | ``` 111 | 112 | When you run these commands via `pytest --verbose` you should see informative test info being run. 113 | 114 | If you're wondering why you'd want to write markdown in a docstring feel free to check out [mkdocstrings](https://github.com/mkdocstrings/mkdocstrings). 115 | 116 | ## Bash Support 117 | 118 | Be default, bash code blocks are also supported. A markdown file that contains 119 | both python and bash code blocks can have each executed separately. 120 | 121 | This will print the python version to the terminal 122 | 123 | ```bash 124 | python --version 125 | ``` 126 | 127 | This will print the exact same version string 128 | 129 | ```python 130 | import sys 131 | 132 | print(f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}") 133 | ``` 134 | 135 | This markdown could be fully tested like this 136 | 137 | ```python 138 | import pathlib 139 | 140 | from mktestdocs import check_md_file 141 | 142 | fpath = pathlib.Path("docs") / "bash-support.md" 143 | 144 | check_md_file(fpath=fpath, lang="python") 145 | check_md_file(fpath=fpath, lang="bash") 146 | ``` 147 | 148 | ## Additional Language Support 149 | 150 | You can add support for languages other than python and bash by first 151 | registering a new executor for that language. The `register_executor` function 152 | takes a tag to specify the code block type supported, and a function that will 153 | be passed any code blocks found in markdown files. 154 | 155 | For example if you have a markdown file like this 156 | 157 | ````markdown 158 | This is an example REST response 159 | 160 | ```json 161 | {"body": {"results": ["spam", "eggs"]}, "errors": []} 162 | ``` 163 | ```` 164 | 165 | You could create a json validator that tested the example was always valid json like this 166 | 167 | ```python 168 | import json 169 | import pathlib 170 | 171 | from mktestdocs import check_md_file, register_executor 172 | 173 | def parse_json(json_text): 174 | json.loads(json_text) 175 | 176 | register_executor("json", parse_json) 177 | 178 | check_md_file(fpath=pathlib.Path("docs") / "additional-language-support.md", lang="json") 179 | ``` 180 | -------------------------------------------------------------------------------- /dinosaur.py: -------------------------------------------------------------------------------- 1 | # This file is actually used to mock a module for the tests. 2 | 3 | 4 | class Dinosaur: 5 | def __init__(self): 6 | self.name = "trex" 7 | 8 | @staticmethod 9 | def a(value): 10 | return value 11 | 12 | @classmethod 13 | def b(cls, value): 14 | return value 15 | 16 | def hello(self): 17 | return self.name 18 | 19 | 20 | def roar(): 21 | """ 22 | Does a roar! 23 | """ 24 | return "Roarr!!" 25 | 26 | 27 | def super_roar(): 28 | """ 29 | Does a super roar! 30 | """ 31 | return "Super Roarr!!" 32 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koaning/mktestdocs/e4a97fd91ed1638dd5c122a1d6ff303519dbc8c2/icon.png -------------------------------------------------------------------------------- /mktestdocs/__init__.py: -------------------------------------------------------------------------------- 1 | from mktestdocs.__main__ import ( 2 | register_executor, 3 | check_codeblock, 4 | grab_code_blocks, 5 | check_docstring, 6 | check_md_file, 7 | get_codeblock_members, 8 | ) 9 | 10 | __version__ = "0.2.4" 11 | 12 | __all__ = [ 13 | "__version__", 14 | "register_executor", 15 | "check_codeblock", 16 | "grab_code_blocks", 17 | "check_docstring", 18 | "check_md_file", 19 | "get_codeblock_members", 20 | ] 21 | -------------------------------------------------------------------------------- /mktestdocs/__main__.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import pathlib 3 | import subprocess 4 | import textwrap 5 | 6 | _executors = {} 7 | 8 | 9 | def register_executor(lang, executor): 10 | """Add a new executor for markdown code blocks 11 | 12 | lang should be the tag used after the opening ``` 13 | executor should be a callable that takes one argument: 14 | the code block found 15 | """ 16 | _executors[lang] = executor 17 | 18 | 19 | def exec_bash(source): 20 | """Exec the bash source given in a new subshell 21 | 22 | Does not return anything, but if any command returns not-0 an error 23 | will be raised 24 | """ 25 | command = ["bash", "-e", "-u", "-c", source] 26 | try: 27 | subprocess.run(command, check=True) 28 | except Exception: 29 | print(source) 30 | raise 31 | 32 | 33 | register_executor("bash", exec_bash) 34 | 35 | 36 | def exec_python(source): 37 | """Exec the python source given in a new module namespace 38 | 39 | Does not return anything, but exceptions raised by the source 40 | will propagate out unmodified 41 | """ 42 | try: 43 | exec(source, {"__name__": "__main__"}) 44 | except Exception: 45 | print(source) 46 | raise 47 | 48 | 49 | register_executor("", exec_python) 50 | register_executor("python", exec_python) 51 | 52 | 53 | def get_codeblock_members(*classes): 54 | """ 55 | Grabs the docstrings of any methods of any classes that are passed in. 56 | """ 57 | results = [] 58 | for cl in classes: 59 | if cl.__doc__: 60 | results.append(cl) 61 | for name, member in inspect.getmembers(cl): 62 | if member.__doc__: 63 | results.append(member) 64 | return [m for m in results if len(grab_code_blocks(m.__doc__)) > 0] 65 | 66 | 67 | def check_codeblock(block, lang="python"): 68 | """ 69 | Cleans the found codeblock and checks if the proglang is correct. 70 | 71 | Returns an empty string if the codeblock is deemed invalid. 72 | 73 | Arguments: 74 | block: the code block to analyse 75 | lang: if not None, the language that is assigned to the codeblock 76 | """ 77 | first_line = block.split("\n")[0] 78 | if lang: 79 | if first_line[3:] != lang: 80 | return "" 81 | return "\n".join(block.split("\n")[1:]) 82 | 83 | 84 | def grab_code_blocks(docstring, lang="python"): 85 | """ 86 | Given a docstring, grab all the markdown codeblocks found in docstring. 87 | 88 | Arguments: 89 | docstring: the docstring to analyse 90 | lang: if not None, the language that is assigned to the codeblock 91 | """ 92 | docstring = format_docstring(docstring) 93 | docstring = textwrap.dedent(docstring) 94 | in_block = False 95 | block = "" 96 | codeblocks = [] 97 | for idx, line in enumerate(docstring.split("\n")): 98 | if "```" in line: 99 | if in_block: 100 | codeblocks.append(check_codeblock(block, lang=lang)) 101 | block = "" 102 | in_block = not in_block 103 | if in_block: 104 | block += line + "\n" 105 | return [textwrap.dedent(c) for c in codeblocks if c != ""] 106 | 107 | def format_docstring(docstring): 108 | """Formats docstring to be able to successfully go through dedent.""" 109 | if docstring[:1] != "\n": 110 | return f"\n {docstring}" 111 | return docstring 112 | 113 | def check_docstring(obj, lang=""): 114 | """ 115 | Given a function, test the contents of the docstring. 116 | """ 117 | if lang not in _executors: 118 | raise LookupError( 119 | f"{lang} is not a supported language to check\n" 120 | "\tHint: you can add support for any language by using register_executor" 121 | ) 122 | executor = _executors[lang] 123 | for b in grab_code_blocks(obj.__doc__, lang=lang): 124 | executor(b) 125 | 126 | 127 | def check_raw_string(raw, lang="python"): 128 | """ 129 | Given a raw string, test the contents. 130 | """ 131 | if lang not in _executors: 132 | raise LookupError( 133 | f"{lang} is not a supported language to check\n" 134 | "\tHint: you can add support for any language by using register_executor" 135 | ) 136 | executor = _executors[lang] 137 | for b in grab_code_blocks(raw, lang=lang): 138 | executor(b) 139 | 140 | 141 | def check_raw_file_full(raw, lang="python"): 142 | if lang not in _executors: 143 | raise LookupError( 144 | f"{lang} is not a supported language to check\n" 145 | "\tHint: you can add support for any language by using register_executor" 146 | ) 147 | executor = _executors[lang] 148 | all_code = "" 149 | for b in grab_code_blocks(raw, lang=lang): 150 | all_code = f"{all_code}\n{b}" 151 | executor(all_code) 152 | 153 | 154 | def check_md_file(fpath, memory=False, lang="python"): 155 | """ 156 | Given a markdown file, parse the contents for python code blocks 157 | and check that each independent block does not cause an error. 158 | 159 | Arguments: 160 | fpath: path to markdown file 161 | memory: whether or not previous code-blocks should be remembered 162 | """ 163 | text = pathlib.Path(fpath).read_text() 164 | if not memory: 165 | check_raw_string(text, lang=lang) 166 | else: 167 | check_raw_file_full(text, lang=lang) 168 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from mktestdocs import __version__ 2 | from setuptools import setup, find_packages 3 | 4 | test_packages = ["pytest>=4.0.2"] 5 | 6 | setup( 7 | name="mktestdocs", 8 | version=__version__, 9 | packages=find_packages(exclude=["tests"]), 10 | install_requires=[], 11 | extras_require={ 12 | "test": test_packages, 13 | }, 14 | license="Apache Software License 2.0", 15 | license_files=["LICENSE"] 16 | ) 17 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koaning/mktestdocs/e4a97fd91ed1638dd5c122a1d6ff303519dbc8c2/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from copy import copy 2 | 3 | import pytest 4 | 5 | import mktestdocs 6 | 7 | 8 | @pytest.fixture 9 | def temp_executors(): 10 | old_executors = copy(mktestdocs.__main__._executors) 11 | yield 12 | mktestdocs.__main__._executors = old_executors 13 | -------------------------------------------------------------------------------- /tests/data/bad/a.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ```python 4 | 1 + 1 == 2 5 | ``` 6 | 7 | Some more talk. 8 | 9 | ```python 10 | import random 11 | 12 | random.random() 13 | ``` 14 | 15 | This is not allowed. 16 | 17 | ```python 18 | random.random() 19 | ``` 20 | -------------------------------------------------------------------------------- /tests/data/bad/b.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ```bash 4 | GREETING="hello" 5 | ``` 6 | 7 | Some more talk. 8 | 9 | ```bash 10 | for i in {1..4}; do 11 | echo $i 12 | done 13 | ``` 14 | 15 | This is not allowed. 16 | 17 | ```bash 18 | echo $GREETING 19 | ``` 20 | -------------------------------------------------------------------------------- /tests/data/bad/big-bad.md: -------------------------------------------------------------------------------- 1 | This is another test. 2 | 3 | ```python 4 | a = 1 5 | b = 2 6 | ``` 7 | 8 | This shouldn't work. 9 | 10 | ```python 11 | assert add(1, 2) == 3 12 | ``` 13 | 14 | It uses multiple languages. 15 | 16 | ```bash 17 | GREETING="hello" 18 | ``` 19 | 20 | This also shouldn't work. 21 | 22 | ```bash 23 | import math 24 | ``` 25 | -------------------------------------------------------------------------------- /tests/data/good/a.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ```python 4 | 1 + 1 == 2 5 | ``` 6 | 7 | Some more talk. 8 | 9 | ```python 10 | import random 11 | 12 | random.random() 13 | ``` 14 | -------------------------------------------------------------------------------- /tests/data/good/b.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ```bash 4 | GREETING="hello" 5 | ``` 6 | 7 | Some more talk. 8 | 9 | ```bash 10 | for i in {1..4}; do 11 | echo $i 12 | done 13 | ``` 14 | -------------------------------------------------------------------------------- /tests/data/good/big-good.md: -------------------------------------------------------------------------------- 1 | This is another test. 2 | 3 | ```python 4 | from operator import add 5 | a = 1 6 | b = 2 7 | ``` 8 | 9 | Using multiple languages. 10 | 11 | ```bash 12 | let MKTEST_VAR=2**4 13 | ``` 14 | 15 | This should work. 16 | 17 | ```python 18 | assert add(1, 2) == 3 19 | ``` 20 | 21 | This should also work. 22 | 23 | ```bash 24 | for i in {1..$MKTEST_VAR}; do 25 | echo $i 26 | done 27 | ``` 28 | -------------------------------------------------------------------------------- /tests/data/good/c.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ``` 4 | foo="Just a string. But in what language?" 5 | ``` 6 | 7 | Empty code block 8 | 9 | ``` 10 | ``` 11 | -------------------------------------------------------------------------------- /tests/data/good/d.md: -------------------------------------------------------------------------------- 1 | Talk talk talk. 2 | 3 | ```python 4 | 1 + 1 == 2 5 | ``` 6 | -------------------------------------------------------------------------------- /tests/docs/additional-language-support.md: -------------------------------------------------------------------------------- 1 | This is an example REST response 2 | 3 | ```json 4 | {"body": {"results": ["spam", "eggs"]}, "errors": []} 5 | ``` 6 | -------------------------------------------------------------------------------- /tests/docs/bash-support.md: -------------------------------------------------------------------------------- 1 | This will print the python version to the terminal 2 | 3 | ```bash 4 | python --version 5 | ``` 6 | 7 | This will print the exact same version string 8 | 9 | ```python 10 | import sys 11 | 12 | print(f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}") 13 | ``` 14 | -------------------------------------------------------------------------------- /tests/docs/multiple-code-blocks.md: -------------------------------------------------------------------------------- 1 | This is a code block 2 | 3 | ```python 4 | from operator import add 5 | a = 1 6 | b = 2 7 | ``` 8 | 9 | This code-block should run fine. 10 | 11 | ```python 12 | assert add(1, 2) == 3 13 | ``` 14 | -------------------------------------------------------------------------------- /tests/docs/test.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koaning/mktestdocs/e4a97fd91ed1638dd5c122a1d6ff303519dbc8c2/tests/docs/test.md -------------------------------------------------------------------------------- /tests/test_actual_docstrings.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from mktestdocs import check_docstring 3 | 4 | 5 | def foobar_good(a, b): 6 | """ 7 | Returns a + b. 8 | 9 | Examples: 10 | 11 | ```python 12 | import random 13 | 14 | random.random() 15 | assert 'a' + 'b' == 'ab' 16 | assert 1 + 2 == 3 17 | ``` 18 | """ 19 | pass 20 | 21 | 22 | def foobar_also_good(a, b): 23 | """ 24 | ```python 25 | import random 26 | 27 | assert random.random() < 10 28 | ``` 29 | """ 30 | pass 31 | 32 | 33 | def foobar_bad(a, b): 34 | """ 35 | ```python 36 | assert foobar(1, 2) == 4 37 | ``` 38 | """ 39 | pass 40 | 41 | 42 | def admonition_edge_cases(): 43 | """ 44 | !!! note 45 | 46 | All cells of a table are initialized with an empty string. Therefore, to delete the content of a cell, 47 | you need to assign an empty string, i.e. `''`. For instance, to delete the first row after the header: 48 | 49 | ```python 50 | assert 1 + 2 == 3 51 | ```""" 52 | pass 53 | 54 | def adminition_edge_case_bad(): 55 | """Test that we can handle the edge cases of admonitions.""" 56 | example = """!!! note 57 | 58 | Another one. 59 | ```python 60 | assert 1 + 2 == 4 61 | ```""" 62 | pass 63 | 64 | @pytest.mark.parametrize("func", [foobar_good, foobar_also_good, admonition_edge_cases]) 65 | def test_base_docstrings(func): 66 | check_docstring(func) 67 | 68 | 69 | @pytest.mark.parametrize("func", [foobar_bad, adminition_edge_case_bad]) 70 | def test_base_docstrings_bad(func, capsys): 71 | with pytest.raises(Exception): 72 | check_docstring(func) 73 | capsys.readouterr() 74 | assert func.__name__ in capsys.readouterr().out 75 | -------------------------------------------------------------------------------- /tests/test_class.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from mktestdocs import get_codeblock_members, check_docstring 4 | 5 | 6 | class Dinosaur: 7 | """ 8 | This is a dino. 9 | 10 | ```python 11 | from dinosaur import Dinosaur 12 | 13 | assert Dinosaur().name == 'trex' 14 | ``` 15 | """ 16 | 17 | def __init__(self): 18 | self.name = "trex" 19 | 20 | @staticmethod 21 | def a(value): 22 | """ 23 | Returns value 24 | 25 | Example: 26 | 27 | ```python 28 | from dinosaur import Dinosaur 29 | 30 | dino = Dinosaur() 31 | assert dino.a(1) == 1 32 | ``` 33 | """ 34 | return value 35 | 36 | @classmethod 37 | def b(cls, value): 38 | """ 39 | Returns value 40 | 41 | Example: 42 | 43 | ```python 44 | from dinosaur import Dinosaur 45 | assert Dinosaur.b(1) == 1 46 | ``` 47 | """ 48 | return value 49 | 50 | def hello(self): 51 | """ 52 | Returns value 53 | 54 | Example: 55 | 56 | ```python 57 | from dinosaur import Dinosaur 58 | assert Dinosaur().name == 'trex' 59 | ``` 60 | """ 61 | return self.name 62 | 63 | 64 | members = get_codeblock_members(Dinosaur) 65 | 66 | 67 | def test_grab_methods(): 68 | assert len(get_codeblock_members(Dinosaur)) == 4 69 | 70 | 71 | @pytest.mark.parametrize("obj", members, ids=lambda d: d.__qualname__) 72 | def test_member(obj): 73 | check_docstring(obj) 74 | -------------------------------------------------------------------------------- /tests/test_codeblock.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from mktestdocs import check_codeblock, grab_code_blocks 4 | 5 | exibit_a = """ 6 | This is an example docstring. 7 | 8 | Arguments: 9 | a: a parameter 10 | 11 | There is no example 12 | """ 13 | 14 | exibit_b = """ 15 | This is an example docstring. 16 | 17 | Arguments: 18 | a: a parameter 19 | 20 | ```python 21 | assert 1 == 1 22 | ``` 23 | """ 24 | 25 | exibit_c = """ 26 | This is an example docstring. 27 | 28 | Arguments: 29 | a: a parameter 30 | 31 | ``` 32 | assert 1 == 1 33 | ``` 34 | 35 | ```python 36 | assert 1 == 1 37 | ``` 38 | """ 39 | 40 | 41 | @pytest.mark.parametrize( 42 | "doc, n", 43 | [(exibit_a, 0), (exibit_b, 1), (exibit_c, 1)], 44 | ids=["exibit_a", "exibit_b", "exibit_c"], 45 | ) 46 | def test_number_of_codeblocks(doc, n): 47 | assert len(grab_code_blocks(doc, lang="python")) == n 48 | 49 | 50 | @pytest.mark.parametrize( 51 | "doc, n", 52 | [(exibit_a, 0), (exibit_b, 1), (exibit_c, 2)], 53 | ids=["exibit_a", "exibit_b", "exibit_c"], 54 | ) 55 | def test_number_of_codeblocks_any(doc, n): 56 | assert len(grab_code_blocks(doc, lang=None)) == n 57 | -------------------------------------------------------------------------------- /tests/test_format_docstring.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from mktestdocs import get_codeblock_members 4 | from mktestdocs.__main__ import format_docstring 5 | 6 | 7 | def test_docstring_formatted(): 8 | # given (a docstring not prepared for dedent) 9 | docstring = "Some class with a header and a code block" 10 | # when (we go through the format_docstring function) 11 | formatted = format_docstring(docstring) 12 | # then (a new line and tab are added to the docstring) 13 | assert formatted == "\n Some class with a header and a code block" 14 | 15 | def test_docstring_not_formatted(): 16 | # given (a docstring prepared for dedent) 17 | docstring = "\n Some class with a header and a code block" 18 | # when (we go through the format_docstring function) 19 | formatted = format_docstring(docstring) 20 | # then (the docstring doesn't change) 21 | assert formatted == docstring 22 | 23 | 24 | 25 | # The docstring of the first class starts like 26 | # """Some class ... 27 | # The docstring of the second class starts like 28 | # """ 29 | # Some class ... 30 | # The tests are checking that regardless of how the class docstring starts we should always be able to read the tests 31 | class BadClass: 32 | """Some class with a header and a code block. 33 | 34 | ```python 35 | assert False, "this should fail." 36 | ``` 37 | 38 | """ 39 | def __init__(self): 40 | pass 41 | 42 | class BadClassNewLine: 43 | """ 44 | Some class with a header and a code block. 45 | 46 | ```python 47 | assert False, "this should fail." 48 | ``` 49 | 50 | """ 51 | def __init__(self): 52 | pass 53 | 54 | 55 | 56 | @pytest.mark.parametrize("cls", [BadClass, BadClassNewLine], ids=lambda d: d.__qualname__) 57 | def test_grab_bad_methods(cls): 58 | bad_members = get_codeblock_members(cls) 59 | assert len(bad_members) == 1 60 | 61 | 62 | -------------------------------------------------------------------------------- /tests/test_markdown.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import pytest 3 | from shutil import which 4 | from unittest.mock import Mock 5 | 6 | from mktestdocs import check_md_file, register_executor 7 | from mktestdocs.__main__ import exec_bash 8 | 9 | 10 | @pytest.mark.parametrize("fpath", pathlib.Path("tests/data/good").glob("?.md"), ids=str) 11 | def test_files_good(fpath): 12 | check_md_file(fpath=fpath) 13 | 14 | 15 | def test_files_bad(): 16 | fpath = pathlib.Path("tests") / "data" / "bad" / "a.md" 17 | with pytest.raises(Exception): 18 | check_md_file(fpath=fpath) 19 | 20 | 21 | def test_big_files_good(): 22 | """Confirm that we can deal with multi-cell markdown cells.""" 23 | check_md_file(fpath="tests/data/good/big-good.md", memory=True) 24 | 25 | 26 | def test_big_file_independant(): 27 | """Confirm that different files don't influence each other.""" 28 | check_md_file(fpath="tests/data/good/big-good.md", memory=True) 29 | with pytest.raises(Exception): 30 | check_md_file(fpath="tests/data/bad/big-bad.md", memory=True) 31 | 32 | 33 | @pytest.mark.skipif(which("bash") is None, reason="No bash shell available") 34 | @pytest.mark.parametrize("fpath", pathlib.Path("tests/data/good").glob("?.md"), ids=str) 35 | def test_files_good_bash(fpath): 36 | check_md_file(fpath=fpath, lang="bash") 37 | 38 | 39 | @pytest.mark.skipif(which("bash") is None, reason="No bash shell available") 40 | def test_files_bad_bash(): 41 | fpath = pathlib.Path("tests") / "data" / "bad" / "b.md" 42 | with pytest.raises(Exception): 43 | check_md_file(fpath=fpath, lang="bash") 44 | 45 | 46 | @pytest.mark.skipif(which("bash") is None, reason="No bash shell available") 47 | def test_big_files_good_bash(): 48 | fpath = pathlib.Path("tests") / "data" / "good" / "big-good.md" 49 | check_md_file(fpath=fpath, memory=True, lang="bash") 50 | 51 | 52 | @pytest.mark.skipif(which("bash") is None, reason="No bash shell available") 53 | def test_big_file_independant_bash(): 54 | fdir = pathlib.Path("tests") / "data" 55 | check_md_file(fpath=fdir / "good" / "big-good.md", memory=True, lang="bash") 56 | with pytest.raises(Exception): 57 | check_md_file(fpath=fdir / "bad" / "big-bad.md", memory=True, lang="bash") 58 | 59 | 60 | def test_files_unmarked_language_default(): 61 | fpath = pathlib.Path("tests") / "data" / "good" / "c.md" 62 | check_md_file(fpath, lang="") 63 | 64 | 65 | @pytest.mark.skipif(which("bash") is None, reason="No bash shell available") 66 | def test_files_unmarked_language_bash(temp_executors): 67 | fpath = pathlib.Path("tests") / "data" / "good" / "c.md" 68 | register_executor("", exec_bash) 69 | check_md_file(fpath, lang="") 70 | 71 | 72 | def test_override_executor(temp_executors): 73 | fpath = pathlib.Path("tests") / "data" / "good" / "a.md" 74 | hijack = Mock() 75 | register_executor("python", hijack) 76 | check_md_file(fpath, lang="python") 77 | hijack.assert_called() 78 | -------------------------------------------------------------------------------- /tests/test_mktestdocs.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | 3 | from mktestdocs import check_md_file 4 | 5 | def test_readme(monkeypatch): 6 | test_dir = pathlib.Path(__file__).parent 7 | fpath = test_dir.parent / "README.md" 8 | monkeypatch.chdir(test_dir) 9 | 10 | check_md_file(fpath=fpath) 11 | --------------------------------------------------------------------------------