File: test_encoding.py

package info (click to toggle)
pytest-doctestplus 1.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 352 kB
  • sloc: python: 1,978; makefile: 13; sh: 7
file content (186 lines) | stat: -rw-r--r-- 4,536 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
import locale
import os
from pathlib import Path
from textwrap import dedent
from typing import Optional
from collections.abc import Callable

import pytest

pytest_plugins = ["pytester"]
IS_CI = os.getenv("CI", "false") == "true"


@pytest.fixture(
    params=[
        ("A", "a", "utf-8"),
        ("☆", "★", "utf-8"),
        ("b", "B", "cp1252"),
        ("☁", "☀", "utf-8"),
    ],
    ids=[
        "Aa-utf8",
        "star-utf8",
        "bB-cp1252",
        "cloud-utf8",
    ],
)
def charset(request):
    return request.param


@pytest.fixture()
def basic_file(tmp_path: Path) -> Callable[[str, str, str], tuple[str, str, str]]:

    def makebasicfile(a, b, encoding: str) -> tuple[str, str, str]:
        """alternative implementation without the use of `testdir.makepyfile`."""

        content = """
            def f():
                '''
                >>> print('{}')
                {}
                '''
                pass
            """

        original = dedent(content.format(a, b))
        expected_result = dedent(content.format(a, a))

        original_file = tmp_path.joinpath("test_basic.py")
        original_file.write_text(original, encoding=encoding)

        expected_diff = dedent(
            f"""
                 >>> print('{a}')
            -    {b}
            +    {a}
            """
        ).strip("\n")

        return str(original_file), expected_diff, expected_result

    return makebasicfile


@pytest.fixture()
def ini_file(testdir) -> Callable[..., Path]:

    def makeini(
        encoding: str | None = None,
    ) -> Path:
        """Create a pytest.ini file with the specified encoding."""

        ini = ["[pytest]"]

        if encoding is not None:
            ini.append(f"doctest_encoding = {encoding}")

        ini.append("")

        p = testdir.makefile(".ini", pytest="\n".join(ini))

        return Path(p)

    return makeini


def test_basic_file_encoding_diff(testdir, capsys, basic_file, charset, ini_file):
    """
    Test the diff from console output is as expected.
    """
    a, b, encoding = charset

    # create python file to test
    file, diff, _ = basic_file(a, b, encoding)

    # create pytest.ini file
    ini = ini_file(encoding=encoding)
    assert ini.is_file(), "setup pytest.ini not created/found"

    testdir.inline_run(
        file,
        "--doctest-plus-generate-diff",
        "-c",
        str(ini),
    )

    stdout, _ = capsys.readouterr()
    assert diff in stdout


def test_basic_file_encoding_overwrite(testdir, basic_file, charset, ini_file):
    """
    Test that the file is overwritten with the expected content.
    """

    a, b, encoding = charset

    # create python file to test
    file, _, expected = basic_file(a, b, encoding)

    # create pytest.ini file
    ini = ini_file(encoding=encoding)
    assert ini.is_file(), "setup pytest.ini not created/found"

    testdir.inline_run(
        file,
        "--doctest-plus-generate-diff",
        "overwrite",
        "-c",
        str(ini),
    )

    assert expected in Path(file).read_text(encoding)


@pytest.mark.skipif(IS_CI, reason="skip on CI")
def test_legacy_diff(testdir, capsys, basic_file, charset):
    """
    Legacy test are supported to fail on Windows, when no encoding is provided.

    On Windows this is cp1252, so "utf-8" are expected to fail while writing test files.
    """
    a, b, _ = charset

    try:
        file, diff, _ = basic_file(a, b, None)
    except UnicodeEncodeError:
        encoding = locale.getpreferredencoding(False)
        reason = f"could not encode {repr(charset)} with {encoding=}"
        pytest.xfail(reason=reason)

    testdir.inline_run(
        file,
        "--doctest-plus-generate-diff",
    )

    stdout, _ = capsys.readouterr()

    assert diff in stdout


@pytest.mark.skipif(IS_CI, reason="skip on CI")
def test_legacy_overwrite(testdir, basic_file, charset):
    """
    Legacy test are supported to fail on Windows, when no encoding is provided.

    On Windows this is cp1252, so "utf-8" are expected to fail while writing test files.
    """

    a, b, _encoding = charset

    try:
        file, _, expected = basic_file(a, b, None)
    except UnicodeEncodeError:
        encoding = locale.getpreferredencoding(False)
        reason = f"could not encode {repr(charset)} with {encoding=}"
        pytest.xfail(reason=reason)

    testdir.inline_run(
        file,
        "--doctest-plus-generate-diff",
        "overwrite",
    )

    assert expected in Path(file).read_text(_encoding)