Skip to content
Become a
Sponsor or follow @15r10nk on
or
for updates

# `` `inline_snapshot.extra`

The following functions are build on top of inline-snapshot and could also be implemented in an extra library.

They are part of inline-snapshot because they are general useful and do not depend on other libraries.

## `` `prints(*, stdout='', stderr='')`

Uses `contextlib.redirect_stderr/stdout` to capture the output and compare it with the snapshots. `dirty_equals.IsStr` can be used to ignore the output if needed.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`stdout` | `Snapshot[str]` | snapshot which is compared to the recorded output | `''`
`stderr` | `Snapshot[str]` | snapshot which is compared to the recorded error output | `''`

original--inline-snapshot=create ignore stdout

    from inline_snapshot import snapshot
    from inline_snapshot.extra import prints
    import sys

    def test_prints():
        with prints(stdout=snapshot(), stderr=snapshot()):
            print("hello world")
            print("some error", file=sys.stderr)

    from inline_snapshot import snapshot
    from inline_snapshot.extra import prints
    import sys

    def test_prints():
        with prints(
            stdout=snapshot("hello world\n"), stderr=snapshot("some error\n")
        ):
            print("hello world")
            print("some error", file=sys.stderr)

    from inline_snapshot import snapshot
    from inline_snapshot.extra import prints
    from dirty_equals import IsStr
    import sys

    def test_prints():
        with prints(
            stdout=IsStr(),
            stderr=snapshot("some error\n"),
        ):
            print("hello world")
            print("some error", file=sys.stderr)

Source code in `cpython3_3.13_inline-snapshot/build/inline_snapshot/extra.py`

     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

    @contextlib.contextmanager
    def prints(*, stdout: Snapshot[str] = "", stderr: Snapshot[str] = ""):
        """Uses `contextlib.redirect_stderr/stdout` to capture the output and
        compare it with the snapshots. `dirty_equals.IsStr` can be used to ignore
        the output if needed.

        Parameters:
            stdout: snapshot which is compared to the recorded output
            stderr: snapshot which is compared to the recorded error output

        === "original"

            <!-- inline-snapshot: first_block outcome-passed=1 outcome-errors=1 -->
            ``` python
            from inline_snapshot import snapshot
            from inline_snapshot.extra import prints
            import sys

            def test_prints():
                with prints(stdout=snapshot(), stderr=snapshot()):
                    print("hello world")
                    print("some error", file=sys.stderr)
            ```

        === "--inline-snapshot=create"

            <!-- inline-snapshot: create outcome-passed=1 outcome-errors=1 -->
            ``` python hl_lines="7 8 9"
            from inline_snapshot import snapshot
            from inline_snapshot.extra import prints
            import sys

            def test_prints():
                with prints(
                    stdout=snapshot("hello world\\n"), stderr=snapshot("some error\\n")
                ):
                    print("hello world")
                    print("some error", file=sys.stderr)
            ```

        === "ignore stdout"

            <!-- inline-snapshot: outcome-passed=1 -->
            ``` python hl_lines="3 9 10"
            from inline_snapshot import snapshot
            from inline_snapshot.extra import prints
            from dirty_equals import IsStr
            import sys

            def test_prints():
                with prints(
                    stdout=IsStr(),
                    stderr=snapshot("some error\\n"),
                ):
                    print("hello world")
                    print("some error", file=sys.stderr)
            ```
        """

        with redirect_stdout(io.StringIO()) as stdout_io:
            with redirect_stderr(io.StringIO()) as stderr_io:
                yield

        assert stderr_io.getvalue() == stderr
        assert stdout_io.getvalue() == stdout

## `` `raises(exception)`

Check that an exception is raised.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`exception` | `Snapshot[str]` | snapshot which is compared with `f"{type}: {message}"` if an exception occurred or `"<no exception>"` if no exception was raised. | required

original--inline-snapshot=create

    from inline_snapshot import snapshot
    from inline_snapshot.extra import raises

    def test_raises():
        with raises(snapshot()):
            1 / 0

    from inline_snapshot import snapshot
    from inline_snapshot.extra import raises

    def test_raises():
        with raises(snapshot("ZeroDivisionError: division by zero")):
            1 / 0

Source code in `cpython3_3.13_inline-snapshot/build/inline_snapshot/extra.py`

    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

    @contextlib.contextmanager
    def raises(exception: Snapshot[str]):
        """Check that an exception is raised.

        Parameters:
            exception: snapshot which is compared with `#!python f"{type}: {message}"` if an exception occurred or `#!python "<no exception>"` if no exception was raised.

        === "original"

            <!-- inline-snapshot: first_block outcome-passed=1 outcome-errors=1 -->
            ``` python
            from inline_snapshot import snapshot
            from inline_snapshot.extra import raises

            def test_raises():
                with raises(snapshot()):
                    1 / 0
            ```

        === "--inline-snapshot=create"

            <!-- inline-snapshot: create outcome-passed=1 outcome-errors=1 -->
            ``` python hl_lines="6"
            from inline_snapshot import snapshot
            from inline_snapshot.extra import raises

            def test_raises():
                with raises(snapshot("ZeroDivisionError: division by zero")):
                    1 / 0
            ```
        """

        try:
            yield
        except Exception as ex:
            msg = str(ex)
            if "\n" in msg:
                assert f"{type(ex).__name__}:\n{ex}" == exception
            else:
                assert f"{type(ex).__name__}: {ex}" == exception
        else:
            assert "<no exception>" == exception

## `` `warns(expected_warnings, /, include_line=False, include_file=False)`

Captures warnings with `warnings.catch_warnings` and compares them against expected warnings.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`expected_warnings` | `Snapshot[List[Warning]]` | Snapshot containing a list of expected warnings. | required
`include_line` | `bool` | If `True`, each expected warning is a tuple `(linenumber, message)`. | `False`
`include_file` | `bool` | If `True`, each expected warning is a tuple `(filename, message)`. | `False`

The format of the expected warning:

- `(filename, linenumber, message)` if both `include_line` and `include_file` are `True`.
- `(linenumber, message)` if only `include_line` is `True`.
- `(filename, message)` if only `include_file` is `True`.
- A string `message` if both are `False`.

original--inline-snapshot=create

    from inline_snapshot import snapshot
    from inline_snapshot.extra import warns
    from warnings import warn

    def test_warns():
        with warns(snapshot(), include_line=True):
            warn("some problem")

    from inline_snapshot import snapshot
    from inline_snapshot.extra import warns
    from warnings import warn

    def test_warns():
        with warns(snapshot([(8, "UserWarning: some problem")]), include_line=True):
            warn("some problem")

Source code in `cpython3_3.13_inline-snapshot/build/inline_snapshot/extra.py`

    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

    @contextlib.contextmanager
    def warns(
        expected_warnings: Snapshot[List[Warning]],
        /,
        include_line: bool = False,
        include_file: bool = False,
    ):
        """
        Captures warnings with `warnings.catch_warnings` and compares them against expected warnings.

        Parameters:
            expected_warnings: Snapshot containing a list of expected warnings.
            include_line: If `True`, each expected warning is a tuple `(linenumber, message)`.
            include_file: If `True`, each expected warning is a tuple `(filename, message)`.

        The format of the expected warning:

        - `(filename, linenumber, message)` if both `include_line` and `include_file` are `True`.
        - `(linenumber, message)` if only `include_line` is `True`.
        - `(filename, message)` if only `include_file` is `True`.
        - A string `message` if both are `False`.

        === "original"

            <!-- inline-snapshot: first_block outcome-passed=1 outcome-errors=1 -->
            ``` python
            from inline_snapshot import snapshot
            from inline_snapshot.extra import warns
            from warnings import warn

            def test_warns():
                with warns(snapshot(), include_line=True):
                    warn("some problem")
            ```

        === "--inline-snapshot=create"

            <!-- inline-snapshot: create fix outcome-passed=1 outcome-errors=1 -->
            ``` python hl_lines="7"
            from inline_snapshot import snapshot
            from inline_snapshot.extra import warns
            from warnings import warn

            def test_warns():
                with warns(snapshot([(8, "UserWarning: some problem")]), include_line=True):
                    warn("some problem")
            ```
        """
        with warnings.catch_warnings(record=True) as result:
            warnings.simplefilter("always")
            yield

        def make_warning(w):
            message = f"{w.category.__name__}: {w.message}"
            if not include_line and not include_file:
                return message
            message = (message,)

            if include_line:
                message = (w.lineno, *message)
            if include_file:
                message = (w.filename, *message)

            return message

        assert [make_warning(w) for w in result] == expected_warnings