Skip to main content

Detect broken Python examples in Markdown.

Project description

phmutest 0.0.1

Detect broken Python examples in Markdown

  • Command line program checks Python syntax highlighted examples.
  • Equivalent Python library for calling from test suite. | Here
  • Python tools to get fenced code block contents from Markdown. | Here

Treats each Markdown file as a single long example which continues across multiple Markdown fenced code blocks (FCBs or blocks).

  • Checks either Python code examples plus output or ">>>" REPL examples | doctest.
  • Reports pass/failed/error/skip status and line number for each block.
  • An example can continue across files.
  • Runs files in user specified order.
  • TOML configuration available.

Your Python setup and cleanup

Specify a Python function which is called first before checking examples. Change context, acquire resources, create objects, register cleanup functions. Pass objects as global variables to the examples. Cleans up even when fail-fast. | Suite initialization and cleanup

No Markdown edits required for above features

Tests Python examples as is, the same way they were written.

Extendable

Designated and stable patch points for Python standard library unittest.mock.patch() patches. | Here

Advanced features

These features require adding tool specific HTML comment directives to the Markdown. Because directives are HTML comments they are not visible in rendered Markdown. View directives on Latest README on GitHub by pressing the Code button in the banner at the top of the file. | Here.

  • Assign test group names to blocks. Command line options select or deselect test groups by name.
  • Skip blocks or skip checking printed output.
  • Label any fenced code block for later retrieval.
  • Accepts phmdoctest directives except share-names and clear-names.
  • Specify blocks as setup and teardown code for the file or setup across files.

main branch status

Code style: black

CI Build status readthedocs codecov

Docs RTD | Docs GitHub | Repos | pytest | Codecov | License

Installation | Usage | FILE | REPL mode | Suite initialization and cleanup | Extend an example across files | Skip blocks from the command line | --summary | TOML configuration | Run as a Python module | Call from Python | Patch points | Related projects

Changes | Contributions

Core feature demo

markdown

The are no phmutest directives in this file. The example starts by creating the object m.

from hashlib import sha256
m = sha256()

The example continues here.

m.update(b"hello World")
print(m.hexdigest()[0:5])

Expected output here is checked. This fenced code block does not have an info string.

db406

The example continues here. It will continue for the entire file. This is the last Python fenced code block (FCB) in the file.

m.update(b"more bytes")
print(m.hexdigest()[0:5])

Note the expected output is different.

4c6ea

phmutest command line

phmutest README.md --log

phmutest output

Here is output from the command line. The output produced by Python standard library unittest module is not shown here. This is printed after the unittest OK line.

log:
args.files: 'README.md'
args.log: 'True'

location|label  result
--------------  ------
README.md:92..  pass
README.md:98..  pass
README.md:111.  pass
--------------  ------

See list of demos See How it works

Installation

python -m pip install phmutest
  • No dependencies since Python 3.11. Depends on tomli before Python 3.11.
  • Pure Python. No binaries.
  • It is advisable to install in a virtual environment.

Usage

phmutest --help

usage: phmutest [-h] [--version] [--skip [TEXT ...]] [--fixture DOTTED_PATH.FUNCTION]
                [--share-across-files [FILE ...]] [--setup-across-files [FILE ...]]
                [--select [GROUP ...] | --deselect [GROUP ...]]
                [--config TOMLFILE] [--replmode]
                [-g OUTFILE] [--progress]
                [--sharing [FILE ...]] [--log] [--summary]
                [--report]
                [FILE ...]

Detect broken Python examples in Markdown. Accepts relevant unittest options.

positional arguments:
  FILE                  Markdown input file.

options:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  --skip [TEXT ...]     Any block that contains the substring TEXT is not tested.
  --fixture DOTTED_PATH.FUNCTION
                        Function run before testing.
  --share-across-files [FILE ...]
                        Shares names from Markdown file to later positional files.
  --setup-across-files [FILE ...]
                        Apply Markdown file setup blocks to files.
  --select [GROUP ...]  Select all blocks with phmutest-group GROUP directive for testing.
  --deselect [GROUP ...]
                        Exclude all blocks with phmutest-group GROUP directive from testing.
  --config TOMLFILE     .toml configuration file.
  --replmode            Test Python interactive sessions.
  -g OUTFILE, --generate OUTFILE
                        Write generated Python or docstring to output file or stdout.
  --progress            Print block by block test progress. File by file in --replmode.
  --sharing [FILE ...]  For these files print name sharing. . means all files.
  --log                 Print log items when done.
  --summary             Print test count and skipped tests.
  --report              Print fenced code block configuration, deselected blocks.
  • The -f option indicates fail fast.

FILE

The Markdown files are processed in the same order they are present as positional arguments on the command line. Shell wildcards can be used. Be aware that the shell expansion and operating system will determine the order.

REPL mode

When --replmode is specified Python interactive sessions are tested and Python code and expected output blocks are not tested. REPL mode tests are implemented using doctest. The option --setup-across-files and the setup and teardown directives have no effect in REPL mode. --progress has file by file granularity.

Suite initialization and cleanup

Use --fixture to specify a Python initialization function that runs before the tests. It works with or without --replmode, but there are differences. In both modes, the fixture function may create objects (globs) that are visible as globals to the FCBs under test. In the event of test errors orderly cleanup/release of resources is assured. For Python code blocks the fixture may register cleanup functions by calling unittest.addModuleCleanup(). In REPL mode the fixture function optionally returns a cleanup function.

  • The fixture can acquire and release resources or change context.
  • The fixture can make entries to the log displayed by --log.

Specify the --fixture function as a relative dotted path where / is replaced with .. For example, the function my_init() in the file tests/myfixture.py would be specified:

--fixture tests.myfixture.my_init

The function is passed keyword only arguments and optionally returns a Fixture instance. The keyword arguments and return type are described by src/phmutest/fixture.py. The fixture file should be in the project directory tree. Fixture demos:

Extend an example across files

Names assigned by all the blocks in a file can be shared, as global variables, to files specified later in the command line. Add a markdown file path to the --share-across-files command line option. The 'shared' file(s) must also be specified as a FILE positional command line argument.

Skip blocks from the command line

The skip --skip TEXT command line option prevents testing of any Python code or REPL block that contains the substring TEXT. The block is logged as skip with --skip TEXT as the reason.

summary option

The example here shows --summary output.

TOML configuration

Command line options can be augmented with values from a [tool.phmutest] section in a .toml configuration file. It can be in a new file or added to an existing .toml file like pyproject.toml. The configuration file is specified by the --config FILE command line option.

Zero or more of these TOML keys may be present in the [tool.phmutest] section.

TOML key Usage option TOML value - double quoted strings
include-globs FILE list of filename glob to select files
exclude-globs FILE list of filename glob to deselect files
share-across-files --share-across-files list of path
setup-across-files --setup-across-files list of path
fixture --fixture dotted path
select --select list of group directive name
deselect --deselect list of group directive name

Only one of select and deselect can have strings.

  • globs are described by Python standard library pathlib.Path.glob().
  • Any FILEs on the command line extend the files selected by include-globs and exclude-globs.
  • Command line options supercede the keys in the config file.
  • See the example tests/toml/project.toml.

Run as a Python module

To run phmutest as a Python module:

python -m phmutest README.md --log

Call from Python

Call phmutest.main.main() with a list of strings for the usage arguments, options, and option values like this: ["/md/project.md", "--replmode"]

  • A phmutest.summary.PhmResult instance is returned.
  • When calling from Python there is no shell wildcard expansion.
  • The --fixture function can be in the same Python file.
  • Call from pytest to get overall result as Junit XML | Suggestion

Example | Limitation

Patch points

Feel free to unittest.mock.patch() at these places in the code and not worry about breakage in future versions. Look for examples in tests/test_patching.py.

patched function purpose
phmutest.direct.directive_finders() Add directive aliases
phmutest.fenced.python_matcher() Add detect Python from FCB info string
phmutest.session.modify_docstring() Inspect/modify REPL text before testing
phmutest.reader.post() Inspect/modify DocNode detected in Markdown

List of patch points

Related projects

  • phmdoctest
  • rundoc
  • byexample
  • sphinx.ext.doctest
  • sybil
  • doxec
  • egtest
  • pytest-phmdoctest
  • pytest-codeblocks

MIT License

Copyright (c) 2023 Mark Taylor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

phmutest-0.0.1.tar.gz (103.9 kB view details)

Uploaded Source

Built Distribution

phmutest-0.0.1-py3-none-any.whl (41.4 kB view details)

Uploaded Python 3

File details

Details for the file phmutest-0.0.1.tar.gz.

File metadata

  • Download URL: phmutest-0.0.1.tar.gz
  • Upload date:
  • Size: 103.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for phmutest-0.0.1.tar.gz
Algorithm Hash digest
SHA256 fce0a9589d36b71500048d51634439c73115673a41f0b26270f70ba458c1f9c4
MD5 afe8930a3b35bf9ced0e4459e8290b32
BLAKE2b-256 85d6b585eee3d3f7feb294cebf396c4df6d0b8a6c9203b3d4e22d4170b552b68

See more details on using hashes here.

File details

Details for the file phmutest-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: phmutest-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 41.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for phmutest-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8edb41be67cbc9ed60c7ef004a992df03ea3f17baa04165c3f18eca88abe6886
MD5 b77c96895c9374fba3e309ecdfff064c
BLAKE2b-256 0625bb7b896f4456b84e27413ba19a489636632d906b813cd382202a5f225e77

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page