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
|
# ------------------------------------------------------------------------------
# Copyright (c) 2018-2024, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------------------------------------
import sys
import ast
import pytest
from enaml.core.parser import parse
from .test_parser import validate_ast
TEST_SOURCE = {
"f-string single value": r"""
a = f'test {a:d}'
""",
"f-string multiple values": r"""
a = f'test {a:g}, {b}'
""",
"f-string split 1": r"""
a = (f'{r}' '{t:s}')
""",
"f-string split 2": r"""
a = ('{r}' f'{t:s}')
""",
"f-string raw string": r"""
a = rf'{a}\n'
""",
"f-string raw string 2": r"""
a = fr'{a}\n'
""",
}
for k, v in list(TEST_SOURCE.items()):
TEST_SOURCE[k.replace("f-", "F-")] = v.replace("f'", "F'")
if "rf'" in v:
TEST_SOURCE[k.replace("raw", "RAW")] = v.replace("rf'", "Rf'")
TEST_SOURCE[k.replace("f-", "F-").replace("raw", "RAW")] = v.replace(
"rf'", "RF'"
)
if "fr'" in v:
TEST_SOURCE[k.replace("raw", "RAW")] = v.replace("fr'", "fR'")
TEST_SOURCE[k.replace("f-", "F-").replace("raw", "RAW")] = v.replace(
"fr'", "FR'"
)
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Requires Python 3.6")
@pytest.mark.parametrize("desc", TEST_SOURCE.keys())
def test_f_strings(desc):
"""Test that we produce valid ast for f-strings."""
src = TEST_SOURCE[desc].strip()
print(src)
# Ensure it's valid
py_ast = ast.parse(src)
enaml_ast = parse(src).body[0].ast
validate_ast(py_ast.body[0], enaml_ast.body[0], True)
@pytest.mark.skipif(
(3, 12) < sys.version_info or sys.version_info < (3, 6),
reason="Requires Python 3.6",
)
@pytest.mark.parametrize("source", [("f'{\\}'"), ("('d'\nf'{\\}')")])
def test_reporting_errors_f_strings(source):
"""Test that we properly report error on f-string."""
with pytest.raises(SyntaxError) as e:
parse(source)
assert "backslash" in e.value.args[0]
|