blob: 8eb164c534235db344a1a57fa5055c2f7318f737 [file] [log] [blame]
Anthony Sottile8f615292022-01-15 19:24:05 -05001from __future__ import annotations
2
Anthony Sottile2983d442015-02-10 08:14:53 -08003import textwrap
4
Ken Struys12f02df2015-02-05 19:58:20 -08005import pytest
6
7from pre_commit_hooks.string_fixer import main
8
9TESTS = (
10 # Base cases
Anthony Sottile2983d442015-02-10 08:14:53 -080011 ("''", "''", 0),
12 ('""', "''", 1),
13 (r'"\'"', r'"\'"', 0),
14 (r'"\""', r'"\""', 0),
15 (r"'\"\"'", r"'\"\"'", 0),
Ken Struys12f02df2015-02-05 19:58:20 -080016 # String somewhere in the line
Anthony Sottile2983d442015-02-10 08:14:53 -080017 ('x = "foo"', "x = 'foo'", 1),
Ken Struys12f02df2015-02-05 19:58:20 -080018 # Test escaped characters
Anthony Sottile2983d442015-02-10 08:14:53 -080019 (r'"\'"', r'"\'"', 0),
Ken Struys12f02df2015-02-05 19:58:20 -080020 # Docstring
Anthony Sottile2983d442015-02-10 08:14:53 -080021 ('""" Foo """', '""" Foo """', 0),
Ken Struys12f02df2015-02-05 19:58:20 -080022 (
Anthony Sottilee9aea742017-07-15 12:56:51 -070023 textwrap.dedent(
24 """
Anthony Sottile2983d442015-02-10 08:14:53 -080025 x = " \\
26 foo \\
Ken Struys12f02df2015-02-05 19:58:20 -080027 "\n
Anthony Sottilee9aea742017-07-15 12:56:51 -070028 """,
29 ),
30 textwrap.dedent(
31 """
Anthony Sottile2983d442015-02-10 08:14:53 -080032 x = ' \\
33 foo \\
34 '\n
Anthony Sottilee9aea742017-07-15 12:56:51 -070035 """,
36 ),
Anthony Sottile2983d442015-02-10 08:14:53 -080037 1,
Ken Struys12f02df2015-02-05 19:58:20 -080038 ),
Anthony Sottile2983d442015-02-10 08:14:53 -080039 ('"foo""bar"', "'foo''bar'", 1),
Anthony Sottilef27ee312023-10-07 13:50:33 -040040 pytest.param(
41 "f'hello{\"world\"}'",
42 "f'hello{\"world\"}'",
43 0,
44 id='ignore nested fstrings',
45 ),
Ken Struys12f02df2015-02-05 19:58:20 -080046)
47
48
Anthony Sottile2983d442015-02-10 08:14:53 -080049@pytest.mark.parametrize(('input_s', 'output', 'expected_retval'), TESTS)
50def test_rewrite(input_s, output, expected_retval, tmpdir):
Anthony Sottile711b7302019-05-16 09:42:04 -070051 path = tmpdir.join('file.py')
Anthony Sottilea99475a2016-05-27 14:09:50 -070052 path.write(input_s)
Max Rozentsveygf35bfed2020-05-20 12:07:45 -040053 retval = main([str(path)])
Anthony Sottilea99475a2016-05-27 14:09:50 -070054 assert path.read() == output
Ken Struys12f02df2015-02-05 19:58:20 -080055 assert retval == expected_retval
Anthony Sottile711b7302019-05-16 09:42:04 -070056
57
58def test_rewrite_crlf(tmpdir):
59 f = tmpdir.join('f.py')
60 f.write_binary(b'"foo"\r\n"bar"\r\n')
Max Rozentsveygf35bfed2020-05-20 12:07:45 -040061 assert main((str(f),))
Anthony Sottile711b7302019-05-16 09:42:04 -070062 assert f.read_binary() == b"'foo'\r\n'bar'\r\n"