File: test_docs.py

package info (click to toggle)
python-inline-snapshot 0.23.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,116 kB
  • sloc: python: 6,888; makefile: 34; sh: 28
file content (451 lines) | stat: -rw-r--r-- 12,136 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import itertools
import platform
import re
import sys
import textwrap
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from typing import Dict
from typing import Generic
from typing import List
from typing import Optional
from typing import TypeVar

import pytest

from inline_snapshot import snapshot
from inline_snapshot._flags import Flags
from inline_snapshot.extra import raises
from inline_snapshot.testing import Example


@dataclass
class Block:
    code: str
    code_header: Optional[str]
    block_options: str
    line: int


def map_code_blocks(file: Path, func, fix: bool = False):

    block_start = re.compile("( *)``` *python(.*)")
    block_end = re.compile("```.*")

    header = re.compile("<!--(.*)-->")

    current_code = file.read_text("utf-8")
    new_lines = []
    block_lines: List[str] = []
    is_block = False
    code = None
    indent = ""
    block_start_linenum: Optional[int] = None
    block_options: Optional[str] = None
    code_header = None
    header_line = ""

    for linenumber, line in enumerate(current_code.splitlines(), start=1):
        m = block_start.fullmatch(line)
        if m and not is_block:
            # ``` python
            block_start_linenum = linenumber
            indent = m[1]
            block_options = m[2]
            block_lines = []
            is_block = True
            continue

        if block_end.fullmatch(line.strip()) and is_block:
            # ```
            is_block = False
            assert block_options is not None
            assert block_start_linenum is not None

            code = "\n".join(block_lines) + "\n"
            code = textwrap.dedent(code)
            if file.suffix == ".py":
                code = code.replace("\\\\", "\\")

            try:
                new_block = func(
                    Block(
                        code=code,
                        code_header=code_header,
                        block_options=block_options,
                        line=block_start_linenum,
                    )
                )
            except Exception:
                print(f"error at block at line {block_start_linenum}")
                print(f"{code_header=}")
                print(f"{block_options=}")
                print(code)
                raise

            if new_block.code_header is not None:
                new_lines.append(f"{indent}<!-- {new_block.code_header.strip()} -->")

            new_lines.append(
                f"{indent}``` {('python '+new_block.block_options.strip()).strip()}"
            )

            new_code = new_block.code.rstrip()
            if file.suffix == ".py":
                new_code = new_code.replace("\\", "\\\\")
            new_code = textwrap.indent(new_code, indent)

            new_lines.append(new_code)

            new_lines.append(f"{indent}```")

            header_line = ""
            code_header = None

            continue

        if is_block:
            block_lines.append(line)
            continue

        m = header.fullmatch(line.strip())
        if m:
            # comment <!-- ... -->
            header_line = line
            code_header = m[1].strip()
            continue
        else:
            if header_line:
                new_lines.append(header_line)
                code_header = None
                header_line = ""

        new_lines.append(line)

    new_code = "\n".join(new_lines) + "\n"

    if fix:
        file.write_text(new_code)
    else:
        assert current_code.splitlines() == new_code.splitlines()
        assert current_code == new_code


def test_map_code_blocks(tmp_path):

    file = tmp_path / "example.md"

    def test_doc(
        markdown_code,
        handle_block=lambda block: exec(block.code),
        blocks=[],
        exception="<no exception>",
        new_markdown_code=None,
    ):

        file.write_text(markdown_code)

        recorded_blocks = []

        with raises(exception):

            def test_block(block):
                handle_block(block)
                recorded_blocks.append(block)
                return block

            map_code_blocks(file, test_block, True)
            assert recorded_blocks == blocks
            map_code_blocks(file, test_block, False)

        recorded_markdown_code = file.read_text()
        if recorded_markdown_code != markdown_code:
            assert new_markdown_code == recorded_markdown_code
        else:
            assert new_markdown_code is None

    test_doc(
        """
``` python
1 / 0
```
""",
        exception=snapshot("ZeroDivisionError: division by zero"),
    )

    test_doc(
        """\
text
``` python
print(1 + 1)
```
text
<!-- inline-snapshot: create test -->
``` python hl_lines="1 2 3"
print(1 - 1)
```
text
""",
        blocks=snapshot(
            [
                Block(
                    code="print(1 + 1)\n", code_header=None, block_options="", line=2
                ),
                Block(
                    code="print(1 - 1)\n",
                    code_header="inline-snapshot: create test",
                    block_options=' hl_lines="1 2 3"',
                    line=7,
                ),
            ]
        ),
    )

    def change_block(block):
        block.code = "# removed"
        block.code_header = "header"
        block.block_options = "option a b c"

    test_doc(
        """\
text
``` python
print(1 + 1)
```
""",
        handle_block=change_block,
        blocks=snapshot(
            [
                Block(
                    code="# removed",
                    code_header="header",
                    block_options="option a b c",
                    line=2,
                )
            ]
        ),
        new_markdown_code=snapshot(
            """\
text
<!-- header -->
``` python option a b c
# removed
```
"""
        ),
    )


@pytest.mark.skipif(
    platform.system() == "Windows",
    reason="\\r in stdout can cause problems in snapshot strings",
)
@pytest.mark.skipif(
    sys.version_info[:2] != (3, 12),
    reason="there is no reason to test the doc with different python versions",
)
@pytest.mark.parametrize(
    "file",
    [
        pytest.param(file, id=file.name)
        for file in [
            *(Path(__file__).parent.parent / "docs").rglob("*.md"),
            *(Path(__file__).parent.parent).glob("*.md"),
            *(Path(__file__).parent.parent / "src").rglob("*.py"),
        ]
    ],
)
def test_docs(file, subtests):
    file_test(file, subtests)


T = TypeVar("T")


class Store(Generic[T]):
    value: T

    def __eq__(self, other: Any):
        self.value = other
        return True


def file_test(
    file: Path,
    subtests,
    fix_files: bool = False,
    width: int = 80,
    use_hl_lines: bool = True,
):
    """Test code blocks with the header <!-- inline-snapshot: options ... -->

    where options can be:
        * flags passed to --inline-snapshot=...
        * `first_block` to specify that the input source code should be the current block and not the last
        * `outcome-passed=2` to check for the pytest test outcome
    """

    last_code = None

    std_files = {
        "pyproject.toml": f"""
[tool.black]
line-length={width}
""",
        "conftest.py": """
import datetime
import pytest
from freezegun.api import FakeDatetime,FakeDate
from inline_snapshot import customize_repr

@customize_repr
def _(value:FakeDatetime):
    return value.__repr__().replace("FakeDatetime","datetime.datetime")

@customize_repr
def _(value:FakeDate):
    return value.__repr__().replace("FakeDate","datetime.date")


@pytest.fixture(autouse=True)
def set_time(freezer):
        freezer.move_to(datetime.datetime(2024, 3, 14, 0, 0, 0, 0))
        yield
""",
    }

    extra_files: Dict[str, List[str]] = defaultdict(list)

    def test_block(block: Block):
        if block.code_header is None:
            return block

        if block.code_header.startswith("inline-snapshot-lib:"):
            extra_files[block.code_header.split()[1]].append(block.code)
            return block

        if block.code_header.startswith("todo-inline-snapshot:"):
            return block

        nonlocal last_code
        with subtests.test(line=block.line):

            code = block.code

            options = set(block.code_header.split())

            # if "requires_assert" in options and not is_pytest_compatible():
            #    return block

            if "requires_assert" in options:
                # wen can not test the docs in the no insider version
                return block

            flags = options & Flags.all().to_set()

            args = ["--inline-snapshot", ",".join(flags)] if flags else []

            errors = Store[str]()
            outcomes = Store[Dict[str, int]]()
            returncode = Store[int]()

            if flags and "first_block" not in options:
                assert last_code is not None
                test_files = {"test_example.py": last_code}
            else:
                test_files = {"test_example.py": code}

            example = Example({**std_files, **test_files})
            if extra_files:
                all_files = [
                    [(key, file) for file in files]
                    for key, files in extra_files.items()
                ]
                for files in itertools.product(*all_files):
                    example = example.with_files(dict(files))

                    example = example.run_pytest(
                        args, error=errors, outcomes=outcomes, returncode=returncode
                    )

            else:
                example = example.run_pytest(
                    args, error=errors, outcomes=outcomes, returncode=returncode
                )

            print("flags:", flags, repr(block.block_options))

            new_code = code
            if flags:
                new_code = example.files["test_example.py"]
            new_code.replace("\n\n", "\n")

            if "show_error" in options:
                new_code = new_code.split("# Error:")[0]
                new_code += "# Error:\n" + textwrap.indent(errors.value, "# ")

            print("new code:")
            print(new_code)
            print("expected code:")
            print(code)

            block.code_header = "inline-snapshot: " + " ".join(
                sorted(flags)
                + sorted(options & {"first_block", "show_error", "requires_assert"})
                + [
                    f"outcome-{k}={v}"
                    for k, v in outcomes.value.items()
                    if k in ("failed", "errors", "passed")
                ]
            )

            if use_hl_lines:
                from inline_snapshot._align import align

                linenum = 1
                hl_lines = ""
                if last_code is not None and "first_block" not in options:
                    changed_lines = []
                    alignment = align(last_code.split("\n"), new_code.split("\n"))
                    for c in alignment:
                        if c == "d":
                            continue
                        elif c == "m":
                            linenum += 1
                        else:
                            changed_lines.append(str(linenum))
                            linenum += 1
                    if changed_lines:
                        hl_lines = f'hl_lines="{" ".join(changed_lines)}"'
                    else:
                        assert False, "no lines changed"
                block.block_options = hl_lines
            else:
                pass  # pragma: no cover

            block.code = new_code

            last_code = code
        return block

    map_code_blocks(file, test_block, fix_files)


if __name__ == "__main__":  # pragma: no cover
    import sys

    file = Path(sys.argv[1])

    print(file)

    @contextmanager
    def test(line):
        yield

    nosubtests = SimpleNamespace(test=test)

    file_test(file, nosubtests, fix_files=True, width=60, use_hl_lines=False)