File: test_python.py

package info (click to toggle)
markdown-exec 1.10.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 740 kB
  • sloc: python: 2,497; javascript: 180; makefile: 32; sh: 30
file content (231 lines) | stat: -rw-r--r-- 5,406 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Tests for the Python formatters."""

from __future__ import annotations

import re
from textwrap import dedent
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import pytest
    from markdown import Markdown


def test_output_markdown(md: Markdown) -> None:
    """Assert Markdown is converted to HTML.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="yes"
            print("**Bold!**")
            ```
            """,
        ),
    )
    assert html == "<p><strong>Bold!</strong></p>"


def test_output_html(md: Markdown) -> None:
    """Assert HTML is injected as is.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="yes" html="yes"
            print("**Bold!**")
            ```
            """,
        ),
    )
    assert html == "<p>**Bold!**\n</p>"


def test_error_raised(md: Markdown, caplog: pytest.LogCaptureFixture) -> None:
    """Assert errors properly log a warning and return a formatted traceback.

    Parameters:
        md: A Markdown instance (fixture).
        caplog: Pytest fixture to capture logs.
    """
    html = md.convert(
        dedent(
            """
            ```python exec="yes"
            raise ValueError("oh no!")
            ```
            """,
        ),
    )
    assert "Traceback" in html
    assert "ValueError" in html
    assert "oh no!" in html
    assert "Execution of python code block exited with errors" in caplog.text


def test_can_print_non_string_objects(md: Markdown) -> None:
    """Assert we can print non-string objects.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="yes"
            class NonString:
                def __str__(self):
                    return "string"

            nonstring = NonString()
            print(nonstring, nonstring)
            ```
            """,
        ),
    )
    assert "Traceback" not in html


def test_sessions(md: Markdown) -> None:
    """Assert sessions can be reused.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="1" session="a"
            a = 1
            ```

            ```pycon exec="1" session="b"
            >>> b = 2
            ```

            ```pycon exec="1" session="a"
            >>> print(f"a = {a}")
            >>> try:
            ...     print(b)
            ... except NameError:
            ...     print("ok")
            ... else:
            ...     print("ko")
            ```

            ```python exec="1" session="b"
            print(f"b = {b}")
            try:
                print(a)
            except NameError:
                print("ok")
            else:
                print("ko")
            ```
            """,
        ),
    )
    assert "a = 1" in html
    assert "b = 2" in html
    assert "ok" in html
    assert "ko" not in html


def test_reporting_errors_in_sessions(md: Markdown, caplog: pytest.LogCaptureFixture) -> None:
    """Assert errors and source lines are correctly reported across sessions.

    Parameters:
        md: A Markdown instance (fixture).
        caplog: Pytest fixture to capture logs.
    """
    html = md.convert(
        dedent(
            """
            ```python exec="1" session="a"
            def fraise():
                raise RuntimeError("strawberry")
            ```

            ```python exec="1" session="a"
            print("hello")
            fraise()
            ```
            """,
        ),
    )
    assert "Traceback" in html
    assert "strawberry" in html
    assert "fraise()" in caplog.text
    assert 'raise RuntimeError("strawberry")' in caplog.text


def test_removing_output_from_pycon_code(md: Markdown) -> None:
    """Assert output lines are removed from pycon snippets.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```pycon exec="1" source="console"
            >>> print("ok")
            ko
            ```
            """,
        ),
    )
    assert "ok" in html
    assert "ko" not in html


def test_functions_have_a_module_attribute(md: Markdown) -> None:
    """Assert functions have a `__module__` attribute.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="1"
            def func():
                pass

            print(f"`{func.__module__}`")
            ```
            """,
        ),
    )
    assert "_code_block_n" in html


def test_future_annotations_do_not_leak_into_user_code(md: Markdown) -> None:
    """Assert future annotations do not leak into user code.

    Parameters:
        md: A Markdown instance (fixture).
    """
    html = md.convert(
        dedent(
            """
            ```python exec="1"
            class Int:
                ...

            def f(x: Int) -> None:
                return x + 1.0

            print(f"`{f.__annotations__['x']}`")
            ```
            """,
        ),
    )
    assert "<code>Int</code>" not in html
    assert re.search(r"class '_code_block_n\d+_\.Int'", html)