File: default_encoding_test.py

package info (click to toggle)
pyupgrade 3.21.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 692 kB
  • sloc: python: 10,653; makefile: 3
file content (69 lines) | stat: -rw-r--r-- 2,016 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
from __future__ import annotations

import pytest

from pyupgrade._data import Settings
from pyupgrade._main import _fix_plugins


@pytest.mark.parametrize(
    ('s', 'expected'),
    (
        ('"asd".encode("utf-8")', '"asd".encode()'),
        ('f"asd".encode("utf-8")', 'f"asd".encode()'),
        ('f"{3}asd".encode("utf-8")', 'f"{3}asd".encode()'),
        ('fr"asd".encode("utf-8")', 'fr"asd".encode()'),
        ('r"asd".encode("utf-8")', 'r"asd".encode()'),
        ('"asd".encode("utf8")', '"asd".encode()'),
        ('"asd".encode("UTF-8")', '"asd".encode()'),
        pytest.param(
            '"asd".encode(("UTF-8"))',
            '"asd".encode()',
            id='parenthesized encoding',
        ),
        (
            'sys.stdout.buffer.write(\n    "a"\n    "b".encode("utf-8")\n)',
            'sys.stdout.buffer.write(\n    "a"\n    "b".encode()\n)',
        ),
        (
            'x = (\n'
            '    "y\\u2603"\n'
            ').encode("utf-8")\n',
            'x = (\n'
            '    "y\\u2603"\n'
            ').encode()\n',
        ),
        pytest.param(
            'f"{x}(".encode("utf-8")',
            'f"{x}(".encode()',
            id='3.12+ handle open brace in fstring',
        ),
        pytest.param(
            'f"{foo(bar)}(".encode("utf-8")',
            'f"{foo(bar)}(".encode()',
            id='f-string with function call',
        ),
    ),
)
def test_fix_encode(s, expected):
    ret = _fix_plugins(s, settings=Settings())
    assert ret == expected


@pytest.mark.parametrize(
    's',
    (
        # non-utf-8 codecs should not be changed
        '"asd".encode("unknown-codec")',
        '"asd".encode("ascii")',

        # only autofix string literals to avoid false positives
        'x="asd"\nx.encode("utf-8")',

        # the current version is too timid to handle these
        '"asd".encode("utf-8", "strict")',
        '"asd".encode(encoding="utf-8")',
    ),
)
def test_fix_encode_noop(s):
    assert _fix_plugins(s, settings=Settings()) == s