Package: phmdoctest
phmdoctest 1.4.0IntroductionPython syntax highlighted Markdown doctestCommand line program and Python library to test Python syntax
highlighted code examples in Markdown.Creates apytestPython module that tests Python examples in
README and other Markdown files.Reads these from Markdown fenced code blocks:Python interactive sessions described bydoctest.Python source code and expected terminal output.The test cases get run later by running pytest.Simple use case is possible with no Markdown edits at all.More features selected by adding HTML commentdirectivesto the Markdown.Set test case name.Add a pytest custom marker.Add a pytest.mark.skip decorator.Promote names defined in a test case to module level globals.Label any fenced code block for later retrieval (API).Configurable. Discover and process many Markdown files in a single command.Add inline annotations to comment out sections of code.Get code coverage by running pytest withcoverage.Select Python source code blocks as setup and teardown code.Setup applies to code blocks and optionally to session blocks.An included Python library:Latest Development tools API.Python function returns test file in a string.(testfile() in main.py)Two pytest fixtures.(tester.py)testfile_creatorrunstestfile(). Use with testfile_tester.testfile_testerruns a pytest file with pytest's pytester
in its isolated environment.Runs phmdoctest and can run pytest too.(simulator.py)Functions to read fenced code blocks from Markdown.(tool.py)Test Markdown for Python examples.(tool.py)Prepare directory for generated test files.(tool.py)Extract testsuite tree and list of failing trees from JUnit XML.(tool.py)Available as the pytest pluginpytest-phmdoctest.default branch statusWebsite|Docs|Repos|pytest|Codecov|LicenseIntroduction|Installation|Sample usage|Sample Usage with HTML comment directives|CI usage|--report|Identifying blocks|Directives|skip|label on code and sessions|label on any fenced code block|pytest skip|pytest skipif|setup|teardown|share-names|clear-names|pytest mark decorator|label skip and mark example|setup and teardown example|share-names clear-names example|Configuration|Inline annotations|skipping blocks with --skip|--skip|short form of --skip|--fail-nocode|--setup|--teardown|Setup example|Setup for sessions|Execution context|Send outfile to stdout|Usage|Run as a Python module|Python API|pytest fixtures|Simulate command line|Hints|Directive hints|Related projectsChanges|Contributions|AboutInstallationIt is advisable to install in a virtual environment.python -m pip install phmdoctestSample usageGiven the Markdown fileexample1.mdshown in raw form here...# This is Markdown file example1.md

## Interactive Python session (doctest)

```py
>>> print("Hello World!")
Hello World!
```

## Source Code and terminal output

Code:
```python
from enum import Enum

class Floats(Enum):
    APPLES = 1
    CIDER = 2
    CHERRIES = 3
    ADUCK = 4

for floater in Floats:
    print(floater)
```

sample output:
```
Floats.APPLES
Floats.CIDER
Floats.CHERRIES
Floats.ADUCK
```the command...phmdoctest doc/example1.md --outfile test_example1.pycreates the python source code filetest_example1.pyshown here..."""pytest file built from doc/example1.md"""fromphmdoctest.functionsimport_phm_compare_exactdefsession_00001_line_6():r""">>> print("Hello World!")Hello World!"""deftest_code_14_output_28(capsys):fromenumimportEnumclassFloats(Enum):APPLES=1CIDER=2CHERRIES=3ADUCK=4forfloaterinFloats:print(floater)_phm_expected_str="""\Floats.APPLESFloats.CIDERFloats.CHERRIESFloats.ADUCK"""_phm_compare_exact(a=_phm_expected_str,b=capsys.readouterr().out)Then run a pytest command something like this in your terminal
to test the Markdown session, code, and expected output blocks.pytest --doctest-modulesOr these two commands:pytest
python -m doctest test_example1.pyTheline_6in the function namesession_00001_line_6is the
line number inexample1.mdof the first line
of the interactive session.00001is a sequence number to
order the doctests.The14in the function nametest_code_14_output_28is the
line number of the first line
of python code.28shows the line number of the expected
terminal output.One test case function gets generated for each:Markdown fenced code block interactive sessionPython-code/expected-output Markdown fenced code block pairThe--reportoption below shows the blocks discovered and
how they are tested.Sample Usage with HTML comment directivesGiven the Markdown file shown in raw form here...<!--phmdoctest-mark.skip-->
<!--phmdoctest-label test_example-->
```python
print("Hello World!")
```
```
incorrect expected output
```the command...phmdoctest tests/one_mark_skip.md --outfile test_one_mark_skip.pycreates the python source code file shown here..."""pytest file built from tests/one_mark_skip.md"""importpytestfromphmdoctest.functionsimport_phm_compare_exact@pytest.mark.skip()deftest_example(capsys):print("Hello World!")_phm_expected_str="""\incorrect expected output"""_phm_compare_exact(a=_phm_expected_str,b=capsys.readouterr().out)Run the --outfile with pytest...$ pytest -vv test_one_mark_skip.py

test_one_mark_skip.py::test_example SKIPPEDThe HTML comments in the Markdown are phmdoctestdirectives.Themark.skipdirective adds the @pytest.mark.skip() line.The label directive names the test case function.List ofDirectivesDirectives are optional.Markdown edits are optional.CI usageTest Python examples in README.md in Continuous Integration scripts.
In this snippet for Linux the pytest test suite is in thetestsfolder.mkdirtests/tmp
phmdoctestREADME.md--report--outfiletests/tmp/test_readme.py
pytest--doctest-modules-vvtestsThis console shows testing Python examples in project.md.
Look for the tmp tests at the bottom.Windows Usage on Appveyor.See this excerpt from ci.ymlActions usage example.
It runs on Windows, Linux, and macOS. Please find the phmdoctest command
at the bottom.No changes to README.md are neededhere, look in the last job log.report optionTo see theGFM fenced code blocksin the MARKDOWN_FILE use the--reportoption like this:phmdoctest doc/example2.md --reportwhich lists the fenced code blocks it found in
the fileexample2.md.
Thetest rolecolumn shows how each fenced code block gets tested.doc/example2.md fenced blocks
------------------------------------------------
block     line  test     TEXT or directive
type    number  role     quoted and one per line
------------------------------------------------
python       9  code
            14  output
python      20  code
            26  output
            31  --
python      37  code
python      44  code
            51  output
yaml        59  --
text        67  --
py          75  session
python      87  code
            94  output
py         102  session
------------------------------------------------
7 test cases.
1 code blocks with no output block.Identifying blocksThe PYPIcommonmarkproject provides code to extract fenced code
blocks from Markdown. SpecificationCommonMark Specand websiteCommonMark.Python code, expected output, and Python interactive sessions get extracted.OnlyGFM fenced code blocksare considered.A block is a session block if the info_string starts withpyand the first line of the block starts with the
session prompt:'>>> '.To be treated as Python code the opening fence should start
with one of these:```python
```python3
```py3plus the block contents can't start with'>>> '.The examples use the info_stringspythonfor code andpyfor sessions
since they render with coloring on GitHub, readthedocs, GitHub Pages,
and Python package index.project.mdhas more examples of code and session blocks.It is ok if theinfo stringis laden with additional text, it will be ignored.  The
entire info string will be shown in the block type column of the
report.An output block is a fenced code block that immediately follows a
Python block and starts with an opening fence like this which
has an empty info string.```A Python code block has no output
if it is followed by any of:Python code blockPython session blocka fenced code block with a non-empty info stringTest code gets generated for it, but there will be no
assertion statement.DirectivesDirectives are HTML comments containing test generation commands.
They are edited into the Markdown file immediately before a fenced
code block. It is OK if other HTML comments are present.
See the<!--phmdoctest-skip-->directive in the
raw Markdown below.
With the skip directive no test code will be
generated from the fenced code block.<!--phmdoctest-skip-->
<!--Another HTML comment-->
```python
print("Hello World!")
```
Expected Output
```
Hello World!
```List of DirectivesDirective HTML comment      |    Use on blocks
---------------------------------- | ---------------------
<!--phmdoctest-skip-->             | code, session, output
<!--phmdoctest-label IDENTIFIER--> | code, session
<!--phmdoctest-label TEXT-->       | any
<!--phmdoctest-mark.skip-->        | code
<!--phmdoctest-mark.skipif<3.N-->  | code
<!--phmdoctest-setup-->            | code
<!--phmdoctest-teardown-->         | code
<!--phmdoctest-share-names-->      | code
<!--phmdoctest-clear-names-->      | code
<!--phmdoctest-mark.ATTRIBUTE-->   | codeDirective hintsskipThe skip directive or--skip TEXTcommand line option
prevents code generation for the code or session block.
The skip directive can be placed on an expected output block.
There it prevents checking expected against actual output.Example.label on code and sessionsWhen used on a Python code block or session the label directive
changes the name of the generated test function.Example.Two generated tests, the first without a label,
shown in pytest -v terminal output:test_readme.py::test_code_93 FAILED
test_readme.py::test_beta_feature FAILEDlabel on any fenced code blockOn any fenced code block, the label directive identifies the block
for later retrieval by the classphmdoctest.tool.FCBChooser().
TheFCBChooseris used separately from phmdoctest in
a different pytest file. This allows the test developer to write
additional test cases for fenced code blocks that are not handled by
phmdoctest. The directive value can be any string.# This is file doc/my_markdown_file.md

<!--phmdoctest-label my-fenced-code-block-->
```
The label directive can be placed on any fenced code block.
```Here is Python code to fetch it:importphmdoctest.toolchooser=phmdoctest.tool.FCBChooser("doc/my_markdown_file.md")contents=chooser.contents(label="my-fenced-code-block")print(contents)Output:The label directive can be placed on any fenced code block.pytest skipThe<!--phmdoctest-mark.skip-->directive generates a test
case with a@pytest.mark.skip()decorator.Example.pytest skipifThe<!--phmdoctest-mark.skipif<3.N-->directive generates
a test case with the pytest decorator@pytest.mark.skipif(sys.version_info < (3, N), reason="requires >=py3.N").
N is a Python minor version number.Example.setupA single Python code block can assign names visible to
other code blocks by adding a setup directive or
using the--setupcommand line option.Names assigned by the setup block
get copied to the test module's global namespace after
the setup block runs.Here is an example setup block fromsetup.md:importmathmylist=[1,2,3]a,b=10,11defdoubler(x):returnx*2Using setup modifies the execution context of the
Python code blocks in the Markdown file.
The namesmath,mylist,a,b, anddoublerare visible
to the other Python code blocks. The objects can be modified.Example.teardownSelects a single Python code block that runs
at test module teardown time.
A teardown block can also be designated
using the--teardowncommand line option.Example.share-namesNames assigned by the Python code block get copied to
the test module as globals after the test code runs. This happens at run
time. These names are now visible to subsequent
test cases generated for Python code blocks in the Markdown file.
share-names modifies the execution context as described for
the setup directive above.
The share-names directive can be used on more than one
code block.Example.This directive effectively joins its Python code block to the
following Python code blocks in the Markdown file.clear-namesAfter the test case generated for the Python code block
with the clear-names directive runs, all names that were
created by one or more preceding share-names directives
get deleted. The names that were shared are no longer visible.
This directive also deletes the names assigned by setup.Example.pytest mark decoratorThe<!--phmdoctest-mark.ATTRIBUTE-->directive adds
a @pytest.mark.ATTRIBUTE decorator to the
generated test function. ATTRIBUTE is a valid Python attribute
identifier. This defines a marker to pytest that is used to
select and deselect tests. See the pytest documentation section
"Working with custom markers".
The filemark_example.mdcontains
example usage of the user defined marker "slow". It generatestest_mark_example.pylabel skip and mark exampleThe filedirective1.mdcontains
example usage of label, skip, and mark directives.
The command below generatestest_directive1.py.phmdoctest doc/directive1.md --reportproduces thisreport.phmdoctest doc/directive1.md --outfile test_directive1.pysetup and teardown exampleThe filedirective2.mdcontains
example usage of label, skip, and mark directives.
The command below generatestest_directive2.py.phmdoctest doc/directive2.md --reportproduces thisreport.phmdoctest doc/directive2.md --outfile test_directive2.pyshare-names clear-names exampleThe filedirective3.mdcontains
example usage of share-names and clear-names directives.
The command below generatestest_directive3.py.phmdoctest doc/directive3.md --reportproduces thisreport.phmdoctest doc/directive3.md --outfile test_directive3.pyConfigurationSupply a .ini, .cfg, or .toml configuration file in place of the Markdown file.
Configuration features:Choose Markdown files for test file generation. (glob wildcards).Exclude Markdown files from test file generation. (glob wildcards).Name the output directory.Removes stale test files from output directory.Enable printing.Place a[tool.phmdoctest]section in the configuration file.How to configure.Inline annotationsInline annotations comment out sections of code.
They can be added to the end of lines in Python code blocks.
They should be in a comment.phmdoctest:omitcomments out a section of code.  The line it is on,
plus following lines at greater indent get commented out.phmdoctest:passcomments out one line of code and prepends the pass statement.Here is a snippet showing how to placephmdoctest:passin the code.
The second block shows the code that is generated. Note there is no#immediately beforephmdoctest:pass. It is not required.importtimedeftakes_too_long():time.sleep(100)# delay for awhile. phmdoctest:passtakes_too_long()importtimedeftakes_too_long():pass# time.sleep(100)    # delay for awhile. phmdoctest:passtakes_too_long()Usephmdoctest:omiton single or multi-line statements. Note the two
commented out time.sleep(99). They follow and are indented more
that theif condition:line withphmdoctest:omit.importtime# phmdoctest:omitcondition=Trueifcondition:# phmdoctest:omittime.sleep(99)time.sleep(99)# import time                      # phmdoctest:omitcondition=True# if condition:       # phmdoctest:omit#     time.sleep(99)#     time.sleep(99)Inline annotation processing counts the number of commented
out sections and adds the count as the suffix_Nto the name of the pytest function in the
generated test file.Inline annotations are similar, but less powerful
than the Python standard librarydoctestdirective#doctest+SKIP.
Improper use ofphmdoctest:omitcan cause Python syntax errors.The examples above are snippets that illustrate how to
use inline annotations.
Here is an example that produces a pytest file from Markdown.
The command below takesinline_example.mdand generatestest_inline_example.py.phmdoctest doc/inline_example.md --outfile test_inline_example.pyskipping blocks with skip optionIf you don't want to generate test cases for Python
blocks precede the block with askipdirective or
use the--skip TEXToption. More than oneskipdirective
or--skip TEXTis allowed.The following describes using--skip TEXT.
The code in each Python block gets searched
for the substringTEXT.  Zero, one or more blocks will contain
the substring. These blocks will not generate test cases in the
output file.The Python code in the fenced code block gets searched.The info string isnotsearched.Output blocks arenotsearched.Both Python code and session blocks get searched.Case is significant.The report shows which Python blocks get skipped
in the test role column, and the Python blocks that
matched each --skip TEXT in the skips section.This option makes itvery easytoinadvertently excludePython blocks from the test cases.  In the event no test cases get
generated, the option--fail-nocodedescribed below is useful.Three special--skip TEXTstrings work a little differently.
They select one of the first, second, or last of the Python blocks.
Only Python blocks get counted.--skip FIRSTskips the first Python block.--skip SECONDskips the second Python block.--skip LASTskips the final Python block.skip optionThis command using--skip:phmdoctest doc/example2.md --skip "Python 3.7" --skip LAST --report --outfile test_example2.pyProduces the reportdoc/example2.md fenced blocks
-----------------------------------------------------
block     line  test          TEXT or directive
type    number  role          quoted and one per line
-----------------------------------------------------
python       9  code
            14  output
python      20  skip-code     "Python 3.7"
            26  skip-output
            31  --
python      37  code
python      44  code
            51  output
yaml        59  --
text        67  --
py          75  session
python      87  code
            94  output
py         102  skip-session  "LAST"
-----------------------------------------------------
5 test cases.
1 skipped code blocks.
1 skipped interactive session blocks.
1 code blocks with no output block.

  skip pattern matches (blank means no match)
------------------------------------------------
skip pattern  matching code block line number(s)
------------------------------------------------
Python 3.7    20
LAST          102
------------------------------------------------creates the output filetest_example2.pyshort form of skip optionThis is the same command as above using the short-sform of the--skipoption
in two places.
It produces the same report and outfile.phmdoctest doc/example2.md -s "Python 3.7" -sLAST --report --outfile test_example2.pyfail-nocode optionThe--fail-nocodeoption produces a pytest file that will always
fail when no Python code or session blocks get found.Evem if no Python code or session blocks exist in the
Markdown file a pytest file gets generated.
This also happens when--skipeliminates all the
Python code blocks.
The generated pytest file will have the functiondef test_nothing_passes().If the option--fail-nocodeis passed the
function isdef test_nothing_fails()which raises an
assertion.setup optionA single Python code block can assign names visible to
other code blocks by giving the--setup TEXToption.
Please see thesetupdirective above.
The rules forTEXTare the same as for--skip TEXTplus...Only one block can matchTEXT.The block cannot match a block that is skipped.The block cannot be a session block even though session
blocks get searched forTEXT.It is ok if the block has an output block. It will be ignored.teardown optionA single Python code block can supply code run by the pytestteardown_module()fixture. Use the--teardown TEXToption.
Please see theteardowndirective above.
The rules forTEXTare the same as for--setupabove exceptTEXTwon't match a setup block.Setup exampleFor the Markdown filesetup.mdrun this command to see how the blocks get tested.phmdoctest doc/setup.md --setup FIRST --teardown LAST --reportdoc/setup.md fenced blocks
-------------------------------------------------
block     line  test      TEXT or directive
type    number  role      quoted and one per line
-------------------------------------------------
python       9  setup     "FIRST"
python      20  code
            27  output
python      37  code
            42  output
python      47  code
            51  output
python      58  teardown  "LAST"
-------------------------------------------------
3 test cases.This commandphmdoctest doc/setup.md --setup FIRST --teardown LAST --outfile test_setup.pycreates the test filetest_setup.pySetup for sessionsThe pytest option--doctest-modulesis required to
run doctest on sessions.  pytest runs doctests in
a separate context.
For more on this seeExecution contextbelow.To allow sessions to see the variables assigned by the--setupcode block, add the option--setup-doctestHere is an example with setup code and sessionssetup_doctest.md. The first part
of this file is a copy of setup.md.This command  uses the short form of setup and teardown.
-u for setupand -d for teardown.phmdoctest doc/setup_doctest.md -u FIRST -d LAST --setup-doctest --outfile test_setup_doctest.pyIt creates the test filetest_setup_doctest.pyExecution contextWhen run without--setuppytest and doctest determine the order of test case execution.phmdoctest assumes test code and session execution is in file order.Test case order is not significant.Code and expected output run within a function body of a pytest test case.If pytest is invoked with--doctest-modules:Sessions are run in a separate doctest execution context.Otherwise, sessions do not run.With--setupNames assigned by setup code are visible to code blocks.Code blocks can modify the objects created by the setup code.Code block test case order is significant.Session order is not significant.If pytest is run with--doctest-modules:pytest runs two separate contexts: one for sessions, one for code blocks.setup and teardown code gets run twice, once by each context.the names assigned by the setup code block
areare notvisible to the sessions.Withshare-namesOnly following code blocks can modify the shared objects.Shared objects willnotbe visible to sessions
if pytest is run with--doctest-modules.After running a code block withclear-namesShared objects will no longer be visible.Names assigned by setup code will no longer be visible.With--setupand--setup-doctestSame as the setup section plus:names assigned by the setup code block
are visible to the sessions.Sessions can modify the objects created by the setup code.Session order is significant.Sessions and code blocks are still running in separate contexts
isolated from each other.A session can't affect a code block, and a code block can't affect
a session.Names assigned by the setup code block are globally visible
to the entire test suite via the pytest doctest_namespace
fixture.  See hint near the endHints.pytest live logging demoThe live logging demos reveals pytest execution contexts.
pytest Live Logs show the
execution order of setup_module(), test cases, sessions, and
teardown_module().
There are 2 demo invocations in the workflow action
called pytest Live Log Demo.  GitHub login required.Send outfile to stdoutTo redirect the above outfile to the standard output stream use one
of these two commands.Be sure to leave out--reportwhen sending --outfile to standard output.phmdoctest doc/example2.md -s "Python 3.7" -sLAST --outfile -orphmdoctest doc/example2.md -s "Python 3.7" -sLAST --outfile=-Usagephmdoctest --helpUsage: phmdoctest [OPTIONS] MARKDOWN_FILE

  MARKDOWN_FILE may also be .toml, .cfg, or .ini configuration file.

Options:
  --outfile TEXT       Write generated test case file to path TEXT. "-" writes
                       to stdout.

  -s, --skip TEXT      Any Python code or interactive session block that
                       contains the substring TEXT is not tested. More than
                       one --skip TEXT is ok. Double quote if TEXT contains
                       spaces. For example --skip="python 3.7" will skip every
                       Python block that contains the substring "python 3.7".
                       If TEXT is one of the 3 capitalized strings FIRST
                       SECOND LAST the first, second, or last Python code or
                       session block in the Markdown file is skipped.

  --report             Show how the Markdown fenced code blocks are used.

  --fail-nocode        This option sets behavior when the Markdown file has no
                       Python fenced code blocks or interactive session blocks
                       or if all such blocks are skipped. When this option is
                       present the generated pytest file has a test function
                       called test_nothing_fails() that will raise an
                       assertion. If this option is not present the generated
                       pytest file has test_nothing_passes() which will never
                       fail.

  -u, --setup TEXT     The Python code block that contains the substring TEXT
                       is run at test module setup time. Variables assigned at
                       the outer level are visible as globals to the other
                       Python code blocks. TEXT should match exactly one code
                       block. If TEXT is one of the 3 capitalized strings
                       FIRST SECOND LAST the first, second, or last Python
                       code or session block in the Markdown file is matched.
                       A block will not match --setup if it matches --skip, or
                       if it is a session block. Use --setup-doctest below to
                       grant Python sessions access to the globals.

  -d, --teardown TEXT  The Python code block that contains the substring TEXT
                       is run at test module teardown time. TEXT should match
                       exactly one code block. If TEXT is one of the 3
                       capitalized strings FIRST SECOND LAST the first,
                       second, or last Python code or session block in the
                       Markdown file is matched. A block will not match
                       --teardown if it matches either --skip or --setup, or
                       if it is a session block.

--setup-doctest        Make globals created by the --setup Python code block
                       or setup directive visible to session blocks and only
                       when they are tested with the pytest --doctest-modules
                       option.  Please note that pytest runs doctests in a
                       separate context that only runs doctests. This option
                       is ignored if there is no --setup option.

  --version            Show the version and exit.
  --help               Show this message and exit.Run as a Python moduleTo run phmdoctest from the command line:python -m phmdoctest doc/example2.md --reportPython APICallmain.testfile()to generate a pytest file in memory.
Please see the Python APIhere.
The example generates a pytest file from doc/setup.md and
compares the result to doc/test_setup.py.frompathlibimportPathimportphmdoctest.maingenerated_testfile=phmdoctest.main.testfile("doc/setup.md",setup="FIRST",teardown="LAST",)expected=Path("doc/test_setup.py").read_text(encoding="utf-8")assertexpected==generated_testfilepytest fixturesUse fixturetestfile_creatorto generate a test file in memory.
Pass the test file to fixturetestfile_testerto run
the test file in the pytester environment.Fixture API|Example.
See more uses in tests/test_examples.py, tests/test_details.py, and
tests/test_many_markdown.py.
The fixtures run pytest much faster thanrun_and_pytest()below since there is no subprocess call.
In the readthedocs documentation see the section Development tools API 1.4.0.
pytest's pytester is suitable for pytest plugin development.Simulate command lineTo simulate a command line call to phmdoctest from
within a Python scriptphmdoctest.simulatoroffers the
functionrun_and_pytest().it creates the --outfile in a temporary directoryoptionally runs pytest on the outfilepytest can return a JUnit XML reportuseful during development to validate the command line
and prevent use of a stale --outfilePlease see theLatest Development tools API sectionor
the docstring of the functionrun_and_pytest()in the filesimulator.py.Pass pytest_options as a list of strings as shown below.importphmdoctest.simulatorcommand="phmdoctest doc/example1.md --report --outfile temporary.py"simulator_status=phmdoctest.simulator.run_and_pytest(well_formed_command=command,pytest_options=["--doctest-modules","-v"])assertsimulator_status.runner_status.exit_code==0assertsimulator_status.pytest_exit_code==0HintsTo read the Markdown file from the standard input stream.
Use-for MARKDOWN_FILE.Write the test file to a temporary directory so that
it is always up to date.In CI scripts the following shell command will create the temporary
directorytmpin thetestsfolder on Windows, Linux, and macOS.python-c"from pathlib import Path; d = Path('tests') / 'tmp'; d.mkdir(mode=0o700)"It is easy to use --output by mistake instead of--outfile.If Python code block has no output, put assert statements in the code.Use pytest option--doctest-modulesto test the sessions.Markdown indented code blocks (Specsection 4.4) are ignored.simulator_status.runner_status.exit_code == 2 is the click
command line usage error.Since phmdoctest generates code, the input file should be from a trusted
source.An empty code block gets given the roledel-code. It is not tested.Use special TEXT values FIRST, SECOND, LAST for the command
line options--setupand--teardownsince they only match one block.The variable namesmanagenamespace,doctest_namespace,capsys, and_phm_expected_strshould not be used in
Markdown Python code blocks since they may be used in generated code.Setup and teardown code blocks cannot have expected output.To have pytest collect a code block with the label directive
start the value withtest_.With the--setup-doctestoption, names assigned by the setup code
block are globally visible to the entire test suite.
This is due to the scope of the pytest doctest_namespace
fixture.  Try using a separate pytest command to test
just the phmdoctest test.The modulephmdoctest.fixtureis imported at pytest time
to support setup, teardown, share-names, and clear-names features.The phmdoctest Markdown parser finds fenced code blocks enclosed by
html<details>and</details>tags.
The tags may require a preceding and trailing blank line
to render correctly. See example in tests/test_details.py.Try redirecting phmdoctest standard output into PYPI Pygments to
colorize the generated test file.python-mphmdoctestproject.md--outfile-|pygmentizeIf the --outfile is written into a folder that pre-exists in the
repository, consider adding the outfile name to .gitignore. If
the outfile name later changes, the change will be needed in
.gitignore too.# Reserved for generated test file.
tests/test_readme.pyDirective hintsOnly put one of setup, teardown, share-names, or
clear-names on a code block.Only one block can be setup. Only one block can be teardown.The setup or teardown block can't have an expected output block.Label directive does not generate a test
case name on setup and teardown blocks.Directives displayed in the--reportstart with a dash like
this:-label test_i_ratio.Code generated by Python blocks with setup and teardown
directives runs at the pytest fixturescope="module"level.Code generated by Python blocks with share-names and
clear-names directives arecollectedand run by pytest
like any other test case.A malformed HTML comment ending is bad. Make sure
it ends with both dashes like-->.  Running with--reportwill expose that problem.The setup, teardown, share-names, and clear-names directives
have logging. To see the log messages,
run pytest with the option:--log-cli-level=DEBUG --color=yesThere is no limit to number of blank lines after
the directive HTML comment but before the fenced code block.The directive<!--phmdoctest-mark.xfail-->might be useful as
an alternative to<!--phmdoctest-mark.skip-->for failing examples.The directive<!--phmdoctest-mark.ATTRIBUTE-->will not be
effective when used with<!--phmdoctest-setup-->or<!--phmdoctest-teardown-->because pytest marks can only
be applied to tests. They have no effect on fixtures.
Setup and teardown use fixtures.Related projectsrundocbyexamplesphinx.ext.doctestsybildoxecegtestpytest-phmdoctestpytest-codeblocksCopyright (c) 2021 Mark TaylorPermission 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.