|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import pytest |
| 4 | + |
| 5 | +from pyupgrade._data import Settings |
| 6 | +from pyupgrade._main import _fix_plugins |
| 7 | + |
| 8 | + |
| 9 | +@pytest.mark.parametrize( |
| 10 | + 's', |
| 11 | + ( |
| 12 | + pytest.param( |
| 13 | + 'isinstance(x, str)', |
| 14 | + id='isinstance nothing duplicated', |
| 15 | + ), |
| 16 | + pytest.param( |
| 17 | + 'issubclass(x, str)', |
| 18 | + id='issubclass nothing duplicated', |
| 19 | + ), |
| 20 | + pytest.param( |
| 21 | + 'try: ...\n' |
| 22 | + 'except Exception: ...\n', |
| 23 | + id='try-except nothing duplicated', |
| 24 | + ), |
| 25 | + pytest.param( |
| 26 | + 'isinstance(x, (str, (str,)))', |
| 27 | + id='only consider flat tuples', |
| 28 | + ), |
| 29 | + pytest.param( |
| 30 | + 'isinstance(x, (f(), a().g))', |
| 31 | + id='only consider names and dotted names', |
| 32 | + ), |
| 33 | + ), |
| 34 | +) |
| 35 | +def test_constant_fold_noop(s): |
| 36 | + assert _fix_plugins(s, settings=Settings()) == s |
| 37 | + |
| 38 | + |
| 39 | +@pytest.mark.parametrize( |
| 40 | + ('s', 'expected'), |
| 41 | + ( |
| 42 | + pytest.param( |
| 43 | + 'isinstance(x, (str, str, int))', |
| 44 | +
|
| 45 | + 'isinstance(x, (str, int))', |
| 46 | +
|
| 47 | + id='isinstance', |
| 48 | + ), |
| 49 | + pytest.param( |
| 50 | + 'issubclass(x, (str, str, int))', |
| 51 | +
|
| 52 | + 'issubclass(x, (str, int))', |
| 53 | +
|
| 54 | + id='issubclass', |
| 55 | + ), |
| 56 | + pytest.param( |
| 57 | + 'try: ...\n' |
| 58 | + 'except (Exception, Exception, TypeError): ...\n', |
| 59 | +
|
| 60 | + 'try: ...\n' |
| 61 | + 'except (Exception, TypeError): ...\n', |
| 62 | +
|
| 63 | + id='except', |
| 64 | + ), |
| 65 | +
|
| 66 | + pytest.param( |
| 67 | + 'isinstance(x, (str, str))', |
| 68 | +
|
| 69 | + 'isinstance(x, str)', |
| 70 | +
|
| 71 | + id='folds to 1', |
| 72 | + ), |
| 73 | +
|
| 74 | + pytest.param( |
| 75 | + 'isinstance(x, (a.b, a.b, a.c))', |
| 76 | + 'isinstance(x, (a.b, a.c))', |
| 77 | + id='folds dotted names', |
| 78 | + ), |
| 79 | + pytest.param( |
| 80 | + 'try: ...\n' |
| 81 | + 'except(a, a): ...\n', |
| 82 | +
|
| 83 | + 'try: ...\n' |
| 84 | + 'except a: ...\n', |
| 85 | +
|
| 86 | + id='deduplication to 1 does not cause syntax error with except', |
| 87 | + ), |
| 88 | + ), |
| 89 | +) |
| 90 | +def test_constant_fold(s, expected): |
| 91 | + assert _fix_plugins(s, settings=Settings()) == expected |
0 commit comments