codecov[bot]: # [Codecov](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=h1) Report
> Merging [#258](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=desc) into [develop](https://codecov.io/gh/swyddfa/arlunio/commit/9344040dee818cd2ea8a920fc1a6d3f53153e058&el=desc) will **increase** coverage by `2.79%`.
> The diff coverage is `91.17%`.

[![Impacted file tree graph](https://codecov.io/gh/swyddfa/arlunio/pull/258/graphs/tree.svg?width=650&height=150&src=pr&token=TM4SXpcDGy)](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=tree)

```diff
@@             Coverage Diff             @@
##           develop     #258      +/-   ##
===========================================
+ Coverage    60.28%   63.07%   +2.79%     
===========================================
  Files           20       20              
  Lines         1138     1143       +5     
===========================================
+ Hits           686      721      +35     
+ Misses         452      422      -30     
```

| Flag | Coverage Δ | |
|---|---|---|
| #unittests | `63.07% <91.17%> (+2.79%)` | :arrow_up: |

| [Impacted Files](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [arlunio/doc/notebook.py](https://codecov.io/gh/swyddfa/arlunio/pull/258/diff?src=pr&el=tree#diff-YXJsdW5pby9kb2Mvbm90ZWJvb2sucHk=) | `70.09% <91.17%> (+9.66%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=footer). Last update [9344040...ebe4490](https://codecov.io/gh/swyddfa/arlunio/pull/258?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

diff --git a/arlunio/doc/notebook.py b/arlunio/doc/notebook.py
index acacd6a..c70dff2 100644
--- a/arlunio/doc/notebook.py
+++ b/arlunio/doc/notebook.py
@@ -165,7 +165,7 @@ class NotebookTranslator(nodes.NodeVisitor):
     def new_cell(self, cell_type: str) -> None:
         current = self.current_cell
 
-        if current is not None and current.cell_type == cell_type:
+        if current is not None and current.cell_type == cell_type == "markdown":
             return
 
         types = {"markdown": nbf.new_markdown_cell, "code": nbf.new_code_cell}
@@ -201,13 +201,11 @@ class NotebookTranslator(nodes.NodeVisitor):
     visit_legend, depart_legend = no_op
     visit_nbtutorial, depart_nbtutorial = no_op
 
-    def _italics(self, node):
+    def visit_caption(self, caption):
         self.current_cell.source += "*"
 
-    italics = _italics, _italics
-
-    visit_emphasis, depart_emphasis = italics
-    visit_caption, depart_caption = italics
+    def depart_caption(self, caption):
+        self.current_cell.source += "*\n"
 
     def visit_bullet_list(self, node: nodes.bullet_list) -> None:
         self.new_cell("markdown")
@@ -222,6 +220,12 @@ class NotebookTranslator(nodes.NodeVisitor):
     def depart_comment(self, node: nodes.comment) -> None:
         pass
 
+    def visit_emphasis(self, node):
+        self.current_cell.source += "*"
+
+    def depart_emphasis(self, node):
+        self.current_cell.source += "*"
+
     def visit_image(self, node: nodes.image) -> None:
         self.new_cell("markdown")
 
@@ -349,7 +353,7 @@ def codeblock(source: str) -> nodes.literal_block:
     """Construct a valid code block."""
 
     block = nodes.literal_block()
-    block.children = [nodes.Text(source)]
+    block += nodes.Text(source)
 
     return block
 
@@ -409,6 +413,73 @@ class NotebookGalleryBuilder(Builder):
                 f.write(nbf.writes(notebook))
 
 
+def process_solutions(
+    solutions: List[nbsolution], outdir: pathlib.Path, docname: pathlib.Path
+):
+    """Given the solutions for a particular tutorial save them to that tutorial's
+    resource directory.
+
+    The rst content under the solution node will be converted to a python friendly
+    format before being written out as a file under the resources directory.
+    The solution node's children will then be replaced by a pair of codeblocks.
+
+    The first will be a prompt for the user to type out their solution. While the
+    second will contain a :code:`%load` magic that will allow the user to load the
+    actual solution from the resources file into the notebook.
+
+    Parameters
+    ----------
+    solutions:
+        The list of solutions to process.
+    outdir:
+        The output folder the builder is writing to
+    docname:
+        The path (without extension) of the rst file being processed, relative to the
+        project root.
+    """
+    logger.debug("[nbtutorial]: Processing solutions for %s", docname)
+
+    if len(solutions) == 0:
+        return
+
+    soln_dir = outdir / docname.parent / RESOURCE_DIR
+    soln_name = f"{docname.stem}-soln"
+
+    if not soln_dir.exists():
+        soln_dir.mkdir(parents=True)
+
+    for idx, soln in enumerate(solutions):
+        logger.debug("[nbtutorial]: %s", soln)
+
+        soln_fname = f"{soln_name}-{idx + 1:02d}.py"
+        soln_path = soln_dir / soln_fname
+
+        # We need to wrap solutions in a document for some reason
+        doc = new_document("")
+        doc += soln
+
+        # Convert the solution to a valid Python file
+        translator = PythonTranslator(doc)
+        doc.walkabout(translator)
+        python_soln = translator.astext()
+
+        # Insert a couple of code blocks into the notebaook that will
+        # load the solution
+        write_here = "# Write your solution here...\n"
+        load = (
+            "# Execute this cell to load the example solution\n"
+            f"%load {soln_path.relative_to(soln_dir.parent)}"
+        )
+        soln.children = [codeblock(write_here), codeblock(load)]
+
+        # Finally write the actual solution to disk
+        soln_file = soln_dir / soln_fname
+        logger.debug("[nbtutorial]: %s", soln_file)
+
+        with soln_file.open(mode="w") as f:
+            f.write(python_soln)
+
+
 class NotebookTutorialBuilder(Builder):
     """Builder that can convert static tutorials into an interactive jupyer
     notebook."""
@@ -434,52 +505,6 @@ class NotebookTutorialBuilder(Builder):
 
         return uri
 
-    def _process_solutions(
-        self, docname: pathlib.Path, solutions: List[nbsolution]
-    ) -> None:
-        """Given the solutions for a given tutorial save them to the resources dir.
-
-        This also rewrites the doctree so that the solutions are replaced by cells
-        the :code:`%load` magic so that the user can load the results in.
-        """
-        logger.debug("[nbtutorial]: Processing solutions for %s", docname)
-
-        if len(solutions) == 0:
-            return
-
-        soln_dir = pathlib.Path(self.outdir, docname.parent, RESOURCE_DIR)
-        soln_name = docname.stem
-
-        if not soln_dir.exists():
-            soln_dir.mkdir(parents=True)
-
-        for idx, soln in enumerate(solutions):
-            logger.debug("[nbtutorial]: %s", soln)
-
-            soln_fname = f"{soln_name}-{idx + 1:02d}.py"
-            soln_path = soln_dir / soln_fname
-
-            # We need to wrap solutions inside a document for some reason
-            doc = new_document("")
-            doc += soln
-
-            # Convert the solution to a valid Python file
-            translator = PythonTranslator(doc)
-            doc.walkabout(translator)
-            python_soln = translator.astext()
-
-            # Insert a code block into the notebook that will load the solution
-            soln.children = [
-                codeblock(f"%load {soln_path.relative_to(soln_dir.parent)}")
-            ]
-
-            # Write the actual solution to the given file on disk
-            soln_file = os.path.join(soln_dir, soln_fname)
-            logger.debug("[nbtutorial]: --> %s", soln_path)
-
-            with open(soln_file, "w") as f:
-                f.write(python_soln)
-
     def _process_images(self, docname: pathlib.Path, images: List[nodes.image]) -> None:
         """Given the images for a given tutorial, save them to the resources dir."""
         logger.debug("[nbtutorial]: Processing images for %s", docname)
@@ -524,7 +549,7 @@ class NotebookTutorialBuilder(Builder):
 
         # Find and write out any solutions.
         solutions = list(doctree.traverse(condition=nbsolution))
-        self._process_solutions(docname, solutions)
+        process_solutions(solutions, pathlib.Path(self.outdir), docname)
 
         # Find and copy over any images
         images = list(doctree.traverse(condition=nodes.image))

Improve the notebooks that are generated by `nbtutorial`
It would be nice if
- [ ] A new line was generated after an image caption so that it doesn't run into the following paragraph
- [ ] Along with the `%load filepath.py` code cell that is generated, add a second code cell above it which prompts the user for their solution
diff --git a/tests/doc/test_notebook.py b/tests/doc/test_notebook.py
index 186e6e8..d6f07cd 100644
--- a/tests/doc/test_notebook.py
+++ b/tests/doc/test_notebook.py
@@ -1,9 +1,94 @@
 import pathlib
+import tempfile
 
+import docutils.nodes as nodes
 import nbformat.v4 as nbf
 import py.test
 
-from arlunio.doc.notebook import NotebookTranslator
+import arlunio.doc.notebook as notebook
+
+
+def make_solution(src):
+
+    soln = notebook.nbsolution()
+    soln.children = [notebook.codeblock(src)]
+
+    return soln
+
+
+class TestProcessSolutions:
+    """Tests for the process_solutions function."""
+
+    @py.test.mark.parametrize(
+        "docname",
+        [
+            pathlib.Path("users", "index"),
+            pathlib.Path("getting-started"),
+            pathlib.Path("users", "tutorial", "first-example"),
+        ],
+    )
+    def test_make_resources_dir(self, docname):
+        """Ensure that if the resources dir doesn't exist it gets created."""
+
+        soln = make_solution('print("Hello, world!")')
+
+        with tempfile.TemporaryDirectory() as outdir:
+            notebook.process_solutions([soln], pathlib.Path(outdir), docname)
+            assert pathlib.Path(outdir, docname.parent, "resources").exists()
+
+    @py.test.mark.parametrize(
+        "docname",
+        [
+            pathlib.Path("users", "index"),
+            pathlib.Path("getting-started"),
+            pathlib.Path("users", "tutorial", "first-example"),
+        ],
+    )
+    def test_solution_fname(self, docname):
+        """Ensure that an appropriate filename is chosen."""
+
+        soln1 = make_solution('print("hello1")')
+        soln2 = make_solution('print("hello2")')
+        soln3 = make_solution('print("hello3")')
+
+        with tempfile.TemporaryDirectory() as outdir:
+            notebook.process_solutions(
+                [soln1, soln2, soln3], pathlib.Path(outdir), docname
+            )
+
+            for i in range(1, 4):
+                file = pathlib.Path(
+                    outdir,
+                    docname.parent,
+                    "resources",
+                    docname.name + f"-soln-{i:02d}.py",
+                )
+
+                with file.open() as f:
+                    assert f.read() == f'print("hello{i}")'
+
+    def test_rewrites_doctree(self):
+        """Ensure that the doctree is rewritten to load the solution from disk."""
+
+        soln = make_solution("print('Hello, world!')")
+
+        with tempfile.TemporaryDirectory() as outdir:
+            notebook.process_solutions(
+                [soln], pathlib.Path(outdir), pathlib.Path("users")
+            )
+            path = pathlib.Path(outdir, "resources", "users-soln-01.py")
+
+            write, load = soln.children
+
+            assert isinstance(write, nodes.literal_block)
+            assert write.astext() == "# Write your solution here...\n"
+
+            assert isinstance(load, nodes.literal_block)
+            expected = (
+                "# Execute this cell to load the example solution\n"
+                f"%load {path.relative_to(outdir)}"
+            )
+            assert load.astext() == expected
 
 
 @py.test.mark.parametrize(
@@ -34,7 +119,7 @@ def test_notebook_translator(testdata, parse_rst, name):
 
     doctree = parse_rst(rst)
 
-    translator = NotebookTranslator(doctree)
+    translator = notebook.NotebookTranslator(doctree)
     doctree.walkabout(translator)
 
     actual = nbf.writes(translator.asnotebook())

pip install -e .[dev]
parse_log_pytest
pytest
pytest
3.7
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster==0.7.13
anyio==3.7.1
appdirs==1.4.4
argon2-cffi==23.1.0
argon2-cffi-bindings==21.2.0
-e git+https://github.com/swyddfa/arlunio.git@9344040dee818cd2ea8a920fc1a6d3f53153e058#egg=arlunio
attrs @ file:///croot/attrs_1668696182826/work
Babel==2.14.0
backcall==0.2.0
beautifulsoup4==4.13.3
black==23.3.0
bleach==6.0.0
certifi @ file:///croot/certifi_1671487769961/work/certifi
cffi==1.15.1
cfgv==3.3.1
charset-normalizer==3.4.1
click==8.1.8
click-default-group==1.2.4
colorama==0.4.6
coverage==7.2.7
debugpy==1.7.0
decorator==5.1.1
defusedxml==0.7.1
distlib==0.3.9
docutils==0.17.1
entrypoints==0.4
exceptiongroup==1.2.2
fastjsonschema==2.21.1
filelock==3.12.2
flake8==5.0.4
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
hypothesis==6.79.4
identify==2.5.24
idna==3.10
imagesize==1.4.1
importlib-metadata==4.2.0
importlib-resources==5.12.0
incremental==22.10.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
ipykernel==6.16.2
ipython==7.34.0
ipython-genutils==0.2.0
jedi==0.19.2
Jinja2==3.1.6
json5==0.9.16
jsonschema==4.17.3
jupyter-server==1.24.0
jupyter_client==7.4.9
jupyter_core==4.12.0
jupyterlab==3.5.3
jupyterlab-pygments==0.2.2
jupyterlab_server==2.15.2
livereload==2.7.1
MarkupSafe==2.1.5
matplotlib-inline==0.1.6
mccabe==0.7.0
mistune==3.0.2
mypy-extensions==1.0.0
nbclassic==1.2.0
nbclient==0.7.4
nbconvert==7.6.0
nbformat==5.8.0
nest-asyncio==1.6.0
nodeenv==1.9.1
notebook==6.5.7
notebook_shim==0.2.4
numpy==1.21.6
packaging @ file:///croot/packaging_1671697413597/work
pandocfilters==1.5.1
parso==0.8.4
pathspec==0.11.2
pexpect==4.9.0
pickleshare==0.7.5
Pillow==9.5.0
pkgutil_resolve_name==1.3.10
platformdirs==2.6.2
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
pre-commit==2.21.0
prometheus-client==0.17.1
prompt_toolkit==3.0.48
psutil==7.0.0
ptyprocess==0.7.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
Pygments==2.17.2
pyrsistent==0.19.3
pytest==7.1.2
pytest-cov==4.1.0
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.1
pyzmq==26.2.1
requests==2.31.0
Send2Trash==1.8.3
six==1.17.0
sniffio==1.3.1
snowballstemmer==2.2.0
sortedcontainers==2.4.0
soupsieve==2.4.1
Sphinx==4.3.2
sphinx-autobuild==2021.3.14
sphinx-rtd-theme==1.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
sphobjinv==2.3.1
terminado==0.17.1
tinycss2==1.2.1
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
tornado==6.2
towncrier==23.6.0
tox==3.28.0
traitlets==5.9.0
typed-ast==1.5.5
typing_extensions==4.7.1
urllib3==2.0.7
virtualenv==20.16.2
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.6.1
zipp @ file:///croot/zipp_1672387121353/work

name: arlunio
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=22.1.0=py37h06a4308_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2022.12.7=py37h06a4308_0
  - flit-core=3.6.0=pyhd3eb1b0_0
  - importlib_metadata=4.11.3=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=22.0=py37h06a4308_0
  - pip=22.3.1=py37h06a4308_0
  - pluggy=1.0.0=py37h06a4308_1
  - py=1.11.0=pyhd3eb1b0_0
  - pytest=7.1.2=py37h06a4308_0
  - python=3.7.16=h7a1cb2a_0
  - readline=8.2=h5eee18b_0
  - setuptools=65.6.3=py37h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tomli=2.0.1=py37h06a4308_0
  - wheel=0.38.4=py37h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.11.0=py37h06a4308_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - alabaster==0.7.13
      - anyio==3.7.1
      - appdirs==1.4.4
      - argon2-cffi==23.1.0
      - argon2-cffi-bindings==21.2.0
      - arlunio==0.10.0
      - babel==2.14.0
      - backcall==0.2.0
      - beautifulsoup4==4.13.3
      - black==23.3.0
      - bleach==6.0.0
      - cffi==1.15.1
      - cfgv==3.3.1
      - charset-normalizer==3.4.1
      - click==8.1.8
      - click-default-group==1.2.4
      - colorama==0.4.6
      - coverage==7.2.7
      - debugpy==1.7.0
      - decorator==5.1.1
      - defusedxml==0.7.1
      - distlib==0.3.9
      - docutils==0.17.1
      - entrypoints==0.4
      - exceptiongroup==1.2.2
      - fastjsonschema==2.21.1
      - filelock==3.12.2
      - flake8==5.0.4
      - hypothesis==6.79.4
      - identify==2.5.24
      - idna==3.10
      - imagesize==1.4.1
      - importlib-metadata==4.2.0
      - importlib-resources==5.12.0
      - incremental==22.10.0
      - ipykernel==6.16.2
      - ipython==7.34.0
      - ipython-genutils==0.2.0
      - jedi==0.19.2
      - jinja2==3.1.6
      - json5==0.9.16
      - jsonschema==4.17.3
      - jupyter-client==7.4.9
      - jupyter-core==4.12.0
      - jupyter-server==1.24.0
      - jupyterlab==3.5.3
      - jupyterlab-pygments==0.2.2
      - jupyterlab-server==2.15.2
      - livereload==2.7.1
      - markupsafe==2.1.5
      - matplotlib-inline==0.1.6
      - mccabe==0.7.0
      - mistune==3.0.2
      - mypy-extensions==1.0.0
      - nbclassic==1.2.0
      - nbclient==0.7.4
      - nbconvert==7.6.0
      - nbformat==5.8.0
      - nest-asyncio==1.6.0
      - nodeenv==1.9.1
      - notebook==6.5.7
      - notebook-shim==0.2.4
      - numpy==1.21.6
      - pandocfilters==1.5.1
      - parso==0.8.4
      - pathspec==0.11.2
      - pexpect==4.9.0
      - pickleshare==0.7.5
      - pillow==9.5.0
      - pkgutil-resolve-name==1.3.10
      - platformdirs==2.6.2
      - pre-commit==2.21.0
      - prometheus-client==0.17.1
      - prompt-toolkit==3.0.48
      - psutil==7.0.0
      - ptyprocess==0.7.0
      - pycodestyle==2.9.1
      - pycparser==2.21
      - pyflakes==2.5.0
      - pygments==2.17.2
      - pyrsistent==0.19.3
      - pytest-cov==4.1.0
      - python-dateutil==2.9.0.post0
      - pytz==2025.2
      - pyyaml==6.0.1
      - pyzmq==26.2.1
      - requests==2.31.0
      - send2trash==1.8.3
      - six==1.17.0
      - sniffio==1.3.1
      - snowballstemmer==2.2.0
      - sortedcontainers==2.4.0
      - soupsieve==2.4.1
      - sphinx==4.3.2
      - sphinx-autobuild==2021.3.14
      - sphinx-rtd-theme==1.3.0
      - sphinxcontrib-applehelp==1.0.2
      - sphinxcontrib-devhelp==1.0.2
      - sphinxcontrib-htmlhelp==2.0.0
      - sphinxcontrib-jquery==4.1
      - sphinxcontrib-jsmath==1.0.1
      - sphinxcontrib-qthelp==1.0.3
      - sphinxcontrib-serializinghtml==1.1.5
      - sphobjinv==2.3.1
      - terminado==0.17.1
      - tinycss2==1.2.1
      - tornado==6.2
      - towncrier==23.6.0
      - tox==3.28.0
      - traitlets==5.9.0
      - typed-ast==1.5.5
      - typing-extensions==4.7.1
      - urllib3==2.0.7
      - virtualenv==20.16.2
      - wcwidth==0.2.13
      - webencodings==0.5.1
      - websocket-client==1.6.1
prefix: /opt/conda/envs/arlunio

tests/doc/test_notebook.py::TestProcessSolutions::test_make_resources_dir[docname0] tests/doc/test_notebook.py::TestProcessSolutions::test_make_resources_dir[docname1] tests/doc/test_notebook.py::TestProcessSolutions::test_make_resources_dir[docname2] tests/doc/test_notebook.py::TestProcessSolutions::test_solution_fname[docname0] tests/doc/test_notebook.py::TestProcessSolutions::test_solution_fname[docname1] tests/doc/test_notebook.py::TestProcessSolutions::test_solution_fname[docname2] tests/doc/test_notebook.py::TestProcessSolutions::test_rewrites_doctree
tests/doc/test_notebook.py::test_notebook_translator[bare_link] tests/doc/test_notebook.py::test_notebook_translator[bold] tests/doc/test_notebook.py::test_notebook_translator[bullet_list] tests/doc/test_notebook.py::test_notebook_translator[comment] tests/doc/test_notebook.py::test_notebook_translator[doctest_no_output] tests/doc/test_notebook.py::test_notebook_translator[heading] tests/doc/test_notebook.py::test_notebook_translator[image] tests/doc/test_notebook.py::test_notebook_translator[inline_code] tests/doc/test_notebook.py::test_notebook_translator[inline_link] tests/doc/test_notebook.py::test_notebook_translator[italic] tests/doc/test_notebook.py::test_notebook_translator[literal_block] tests/doc/test_notebook.py::test_notebook_translator[paragraphs] tests/doc/test_notebook.py::test_notebook_translator[note]
arlunio/doc/notebook.py
arlunio/doc/notebook.py