MarkdownViewer: a failed or superseded `go()` leaves the history out of step with the document shown

Abierto
#6,780 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
frontend

Línea de trabajo

Read the implementations of MarkdownViewer.go() and Markdown.load(), then find the existing MarkdownViewer tests. Start by adding regression tests for a failed load and for two overlapping go() calls; the issue includes runnable reproductions for both. Done means failed or superseded loads leave the displayed document and navigation history consistent.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Hi! I hit this while writing generated tests against Textual's widgets.

MarkdownViewer.go() pushes the new location onto its Navigator first and then awaits Markdown.load(). Two things follow from that order.

1. A document that fails to load stays in the history. Markdown.load documents that it raises OSError, so an app may catch it. But by then the missing path is the current location, and back() from a later document goes to it and raises again.

import asyncio
import os
import tempfile
from pathlib import Path

import textual
from textual.app import App, ComposeResult
from textual.widgets import MarkdownViewer

class ViewerApp(App):
    def compose(self) -> ComposeResult:
        yield MarkdownViewer()

async def main() -> None:
    os.chdir(tempfile.mkdtemp())
    Path("a.md").write_text("# A doc\n")
    Path("b.md").write_text("# B doc\n")
    app = ViewerApp()
    async with app.run_test() as pilot:
        viewer = app.query_one(MarkdownViewer)
        await viewer.go("a.md")
        try:
            await viewer.go("missing.md")
        except OSError as error:
            print("go(missing.md) raised", type(error).__name__)
        await pilot.pause()
        print("location:", viewer.navigator.location.name)
        print("history: ", [path.name for path in viewer.navigator.stack])
        await viewer.go("b.md")
        try:
            await viewer.back()
        except OSError as error:
            print("back() raised", type(error).__name__)
        print("after back, location:", viewer.navigator.location.name)

print("Textual", textual.__version__)
asyncio.run(main())
Textual 8.2.7
go(missing.md) raised FileNotFoundError
location: missing.md
history:  ['a.md', 'missing.md']
back() raised FileNotFoundError
after back, location: missing.md

I'd expect location: a.md and history: ['a.md'] after the failed go, and back() to return to a.md.

2. Two go() calls in a row aren't ordered. Each pushes its path and then awaits a read in a thread, so whichever read finishes last decides what's shown, while the navigator ends at whichever was called last. This repro starts go("b.md"), then awaits go("a.md") (like clicking one link, then another before the first has loaded). With a slow read for b.md it always disagrees; with no delay at all, it depends on thread timing:

import asyncio
import os
import sys
import tempfile
import time
from pathlib import Path

import textual
from textual.app import App, ComposeResult
from textual.widgets import MarkdownViewer

SLOW = "--no-delay" not in sys.argv
RUNS = int(sys.argv[sys.argv.index("--runs") + 1]) if "--runs" in sys.argv else 1

read_text = Path.read_text

def slow_read_text(self: Path, *args, **kwargs) -> str:
    # Simulate a slow disk (or network file system) for b.md only.
    if SLOW and self.name == "b.md":
        time.sleep(0.2)
    return read_text(self, *args, **kwargs)

Path.read_text = slow_read_text

class ViewerApp(App):
    def compose(self) -> ComposeResult:
        yield MarkdownViewer()

async def main() -> tuple[str, str]:
    app = ViewerApp()
    async with app.run_test() as pilot:
        viewer = app.query_one(MarkdownViewer)
        # The user clicks a link to b.md, then (before it has loaded) a link to a.md.
        first = asyncio.create_task(viewer.go("b.md"))
        await asyncio.sleep(0)  # let it start
        await viewer.go("a.md")
        await first
        await pilot.pause()
        return viewer.navigator.location.name, viewer.document.source.strip()

os.chdir(tempfile.mkdtemp())
Path("a.md").write_text("# A doc\n")
Path("b.md").write_text("# B doc\n")
print("Textual", textual.__version__, "slow b.md" if SLOW else "no delay")
results: dict[tuple[str, str], int] = {}
for _ in range(RUNS):
    result = asyncio.run(main())
    results[result] = results.get(result, 0) + 1
for (location, shown), count in sorted(results.items()):
    print(f"location={location} shows={shown!r}: {count} of {RUNS}")
Textual 8.2.7 slow b.md
location=a.md shows='# B doc': 1 of 1
Textual 8.2.7 no delay
location=a.md shows='# A doc': 125 of 200
location=a.md shows='# B doc': 75 of 200

On main at 5e5b7ef:

Textual 8.2.8 slow b.md
location=a.md shows='# B doc': 1 of 1
Textual 8.2.8 no delay
location=a.md shows='# A doc': 100 of 200
location=a.md shows='# B doc': 100 of 200

In the B doc cases the viewer shows b.md while its location is a.md, so back() and the next relative link both work from the wrong document.

I think both are fixed by adding a location to the history only once its document has loaded, and by having Markdown.load drop a read that a later load call has superseded. I'm happy to send a PR.

Lenguaje dominante
Python
Estrellas
37.7k
Forks
1.5k
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Textualize/textual

Todos los issues de Textualize/textual

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.