File: test_models.py

package info (click to toggle)
hy 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,632 kB
  • sloc: python: 7,299; makefile: 38; sh: 27
file content (276 lines) | stat: -rw-r--r-- 7,316 bytes parent folder | download | duplicates (2)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import copy

import pytest

import hy
from hy.errors import HyWrapperError
from hy.models import (
    Complex,
    Dict,
    Expression,
    FComponent,
    Float,
    FString,
    Integer,
    Keyword,
    List,
    Set,
    String,
    Symbol,
    Tuple,
    as_model,
    pretty,
    replace_hy_obj,
)


def test_symbol_or_keyword():
    for x in ("foo", "foo-bar", "foo_bar", "✈é😂⁂"):
        assert str(Symbol(x)) == x
        assert Keyword(x).name == x
    for x in ("", ":foo", "5", "#foo"):
        # https://github.com/hylang/hy/issues/2383
        with pytest.raises(ValueError):
            Symbol(x)
        assert Keyword(x).name == x
    for x in ("foo bar", "fib()"):
        with pytest.raises(ValueError):
            Symbol(x)
        with pytest.raises(ValueError):
            Keyword(x)


def test_wrap_int():
    wrapped = as_model(0)
    assert type(wrapped) == Integer


def test_wrap_tuple():
    wrapped = as_model((Integer(0),))
    assert type(wrapped) == Tuple
    assert type(wrapped[0]) == Integer
    assert wrapped == Tuple([Integer(0)])


def test_wrap_nested_expr():
    """Test conversion of Expressions with embedded non-HyObjects."""
    wrapped = as_model(Expression([0]))
    assert type(wrapped) == Expression
    assert type(wrapped[0]) == Integer
    assert wrapped == Expression([Integer(0)])


def test_replace_int():
    replaced = replace_hy_obj(0, Integer(13))
    assert replaced == Integer(0)


def test_invalid_bracket_strings():
    for string, brackets in [("]foo]", "foo"), ("something ]f] else", "f")]:
        with pytest.raises(ValueError):
            String(string, brackets)
    for nodes, brackets in [
        ([String("hello"), String("world ]foo]")], "foo"),
        ([String("something"), FComponent([String("world")]), String("]f]")], "f"),
        ([String("something"), FComponent([Integer(1), String("]f]")])], "f"),
    ]:
        with pytest.raises(ValueError):
            FString(nodes, brackets=brackets)


def test_replace_str():
    replaced = replace_hy_obj("foo", String("bar"))
    assert replaced == String("foo")


def test_replace_tuple():
    replaced = replace_hy_obj((0,), Integer(13))
    assert type(replaced) == Tuple
    assert type(replaced[0]) == Integer
    assert replaced == Tuple([Integer(0)])


def test_list_add():
    """Check that adding two Lists generates a List"""
    a = List([1, 2, 3])
    b = List([3, 4, 5])
    c = a + b
    assert c == List([1, 2, 3, 3, 4, 5])
    assert type(c) is List


def test_list_slice():
    """Check that slicing a List produces a List"""
    a = List([1, 2, 3, 4])
    sl1 = a[1:]
    sl5 = a[5:]

    assert type(sl1) == List
    assert sl1 == List([2, 3, 4])
    assert type(sl5) == List
    assert sl5 == List([])


def test_hydict_methods():
    hydict = Dict(["a", 1, "z", 9, "b", 2, "a", 3, "c", 4])
    assert hydict.items() == [("a", 1), ("z", 9), ("b", 2), ("a", 3), ("c", 4)]
    assert hydict.keys() == ["a", "z", "b", "a", "c"]
    assert hydict.values() == [1, 9, 2, 3, 4]


def test_set():
    assert list(Set([3, 1, 2, 2])) == [3, 1, 2, 2]


def test_equality():
    # https://github.com/hylang/hy/issues/1363

    assert String("foo") == String("foo")
    assert String("foo") == hy.as_model("foo")
    assert String("foo") != String("fo")
    assert String("foo") != "foo"
    assert "foo" != String("foo")

    assert Symbol("foo") == Symbol("foo")
    assert Symbol("foo") != Symbol("fo")
    assert Symbol("foo") != String("foo")
    assert Symbol("foo") != "foo"

    assert Integer(5) == Integer(5)
    assert Integer(5) == hy.as_model(5)
    assert Integer(5) != Integer(6)
    assert Integer(5) != 5
    assert 5 != Integer(5)

    l = [Integer(1), Integer(2)]
    assert List(l) == List(l)
    assert List(l) == hy.as_model(l)
    assert List(l) != List(list(reversed(l)))
    assert List(l) != List([Integer(1), Integer(3)])
    assert List(l) != l
    assert List(l) != tuple(l)


def test_number_model_copy():
    i = Integer(42)
    assert i == copy.copy(i)
    assert i == copy.deepcopy(i)

    f = Float(42.0)
    assert f == copy.copy(f)
    assert f == copy.deepcopy(f)

    c = Complex(42j)
    assert c == copy.copy(c)
    assert c == copy.deepcopy(c)


PRETTY_STRINGS = {
    k
    % ("[1.0] {1.0} (1.0) #{1.0}",): v.format(
        """
  hy.models.List([
    hy.models.Float(1.0)]),
  hy.models.Dict([
    hy.models.Float(1.0)  # odd
  ]),
  hy.models.Expression([
    hy.models.Float(1.0)]),
  hy.models.Set([
    hy.models.Float(1.0)])"""
    )
    for k, v in {"[%s]": "hy.models.List([{}])", "#{%s}": "hy.models.Set([{}])"}.items()
}

PRETTY_STRINGS.update(
    {
        "{[1.0] {1.0} (1.0) #{1.0}}": """hy.models.Dict([
  hy.models.List([
    hy.models.Float(1.0)]),
  hy.models.Dict([
    hy.models.Float(1.0)  # odd
  ])
  ,
  hy.models.Expression([
    hy.models.Float(1.0)]),
  hy.models.Set([
    hy.models.Float(1.0)])
  ])""",
        "[1.0 1j [] {} () #{}]": """hy.models.List([
  hy.models.Float(1.0),
  hy.models.Complex(1j),
  hy.models.List(),
  hy.models.Dict(),
  hy.models.Expression(),
  hy.models.Set()])""",
        "{{1j 2j} {1j 2j [][1j]} {[1j][] 1j 2j} {[1j][1j]}}": """hy.models.Dict([
  hy.models.Dict([
    hy.models.Complex(1j), hy.models.Complex(2j)]),
  hy.models.Dict([
    hy.models.Complex(1j), hy.models.Complex(2j),
    hy.models.List(),
    hy.models.List([
      hy.models.Complex(1j)])
    ])
  ,
  hy.models.Dict([
    hy.models.List([
      hy.models.Complex(1j)]),
    hy.models.List()
    ,
    hy.models.Complex(1j), hy.models.Complex(2j)]),
  hy.models.Dict([
    hy.models.List([
      hy.models.Complex(1j)]),
    hy.models.List([
      hy.models.Complex(1j)])
    ])
  ])""",
    }
)


def test_compound_model_repr():
    HY_LIST_MODELS = (Expression, Dict, Set, List)
    with pretty(False):
        for model in HY_LIST_MODELS:
            assert eval(repr(model())).__class__ is model
            assert eval(repr(model([1, 2]))) == model([1, 2])
            assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            # `str` should be pretty, even under `pretty(False)`.
            assert str(hy.read(k)) == v
        for k in PRETTY_STRINGS.keys():
            assert eval(repr(hy.read(k))) == hy.read(k)
    with pretty(True):
        for model in HY_LIST_MODELS:
            assert eval(repr(model())).__class__ is model
            assert eval(repr(model([1, 2]))) == model([1, 2])
            assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            assert repr(hy.read(k)) == v


def test_recursive_model_detection():
    """Check for self-references:
    https://github.com/hylang/hy/issues/2153
    """
    self_ref_list = [1, 2, 3]
    self_ref_dict = {1: 1, 2: 2}
    self_ref_list[1] = self_ref_list
    self_ref_dict[2] = self_ref_dict

    mutually_ref_list = [1, 2, 3]
    mutually_ref_dict = {1: 1, 2: 2}
    mutually_ref_list[1] = mutually_ref_dict
    mutually_ref_dict[2] = mutually_ref_list

    for structure in [
        self_ref_list,
        self_ref_dict,
        mutually_ref_list,
        mutually_ref_dict,
    ]:
        with pytest.raises(HyWrapperError) as exc:
            as_model(structure)
        assert "Self-referential" in str(exc)