File: test_walrus.py

package info (click to toggle)
python-enaml 0.19.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,284 kB
  • sloc: python: 31,443; cpp: 4,499; makefile: 140; javascript: 68; lisp: 53; sh: 20
file content (82 lines) | stat: -rw-r--r-- 1,954 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
#------------------------------------------------------------------------------
# Copyright (c) 2020-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
from textwrap import dedent

import pytest

from enaml.core.parser import parse

from .test_parser import validate_ast

TEST_SOURCE = {
    ':= in expr': r"""
    a = (b := 1)
    """,
    ':= in tuple': r"""
    a = (2, b := 1)
    """,
    ':= in list': r"""
    a = [2, b := 1]
    """,
    ':= in if': r"""
    if b := 1:
        pass
    """,
    ':= in elif': r"""
    a = 0
    if a:
        pass
    elif b := 1:
        pass
    """,
    ':= in while': r"""
    while b := 1:
        pass
    """,
    ':= in function argument': r"""
    f(a, b := c or None)
    """
}


@pytest.mark.skipif(sys.version_info < (3, 8), reason='Requires Python 3.8')
@pytest.mark.parametrize('desc', TEST_SOURCE.keys())
def test_walrus_operator(desc):
    """Test that we produce valid ast use of the := walrus operator.

    """
    src = dedent(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)


TEST_BAD_SOURCE = {
    ':= in while': r"""
    while 2 := 1:
        pass
    """,
    ':= in function argument': r"""
    f(a, 2 := c or None)
    """
}

@pytest.mark.skipif(sys.version_info < (3, 8), reason='Requires Python 3.8')
@pytest.mark.parametrize('desc', TEST_BAD_SOURCE.keys())
def test_invalid_walrus_operator(desc):
    """Test that we produce valid ast use of the := walrus operator.

    """
    src = dedent(TEST_BAD_SOURCE[desc]).strip()
    print(src)
    with pytest.raises(SyntaxError):
        enaml_ast = parse(src).body[0].ast