forked from livebook-dev/pythonx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonx_test.exs
More file actions
464 lines (375 loc) · 11.9 KB
/
pythonx_test.exs
File metadata and controls
464 lines (375 loc) · 11.9 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
defmodule PythonxTest do
use ExUnit.Case, async: true
doctest Pythonx
describe "encode!/1" do
test "atom" do
assert repr(Pythonx.encode!(nil)) == "None"
assert repr(Pythonx.encode!(false)) == "False"
assert repr(Pythonx.encode!(true)) == "True"
assert repr(Pythonx.encode!(:hello)) == "'hello'"
end
test "integer" do
assert repr(Pythonx.encode!(10)) == "10"
assert repr(Pythonx.encode!(-10)) == "-10"
# Large numbers (over 64 bits)
assert repr(Pythonx.encode!(2 ** 100)) == "1267650600228229401496703205376"
end
test "float" do
assert repr(Pythonx.encode!(10.5)) == "10.5"
assert repr(Pythonx.encode!(-10.5)) == "-10.5"
end
test "string" do
assert repr(Pythonx.encode!("hello")) == "b'hello'"
assert repr(Pythonx.encode!("🦊 in a 📦")) ==
~S"b'\xf0\x9f\xa6\x8a in a \xf0\x9f\x93\xa6'"
end
test "binary" do
assert repr(Pythonx.encode!(<<65, 255>>)) == ~S"b'A\xff'"
assert_raise Protocol.UndefinedError, fn ->
Pythonx.encode!(<<1::4>>)
end
end
test "list" do
assert repr(Pythonx.encode!([])) == "[]"
assert repr(Pythonx.encode!([1, 2.0, "hello"])) == "[1, 2.0, b'hello']"
end
test "tuple" do
assert repr(Pythonx.encode!({})) == "()"
assert repr(Pythonx.encode!({1})) == "(1,)"
assert repr(Pythonx.encode!({1, 2.0, "hello"})) == "(1, 2.0, b'hello')"
end
test "map" do
assert repr(Pythonx.encode!(%{"hello" => 1})) == "{b'hello': 1}"
assert repr(Pythonx.encode!(%{2 => nil})) == "{2: None}"
end
test "mapset" do
assert repr(Pythonx.encode!(MapSet.new([1]))) == "{1}"
end
test "identity for Pythonx.Object" do
object = Pythonx.encode!(1)
assert Pythonx.encode!(object) == object
end
test "custom encoder" do
# Contrived example where we encode tuples as lists.
encoder = fn
tuple, encoder when is_tuple(tuple) ->
Pythonx.Encoder.encode(Tuple.to_list(tuple), encoder)
other, encoder ->
Pythonx.Encoder.encode(other, encoder)
end
assert repr(Pythonx.encode!({1, 2}, encoder)) == "[1, 2]"
end
end
describe "decode/1" do
test "none" do
assert Pythonx.decode(eval_result("None")) == nil
end
test "boolean" do
assert Pythonx.decode(eval_result("True")) == true
assert Pythonx.decode(eval_result("False")) == false
end
test "integer" do
assert Pythonx.decode(eval_result("10")) == 10
assert Pythonx.decode(eval_result("-10")) == -10
# Large numbers (over 64 bits)
assert Pythonx.decode(eval_result("2 ** 100")) == 1_267_650_600_228_229_401_496_703_205_376
end
test "float" do
assert Pythonx.decode(eval_result("10.5")) == 10.5
assert Pythonx.decode(eval_result("-10.5")) == -10.5
end
test "string" do
assert Pythonx.decode(eval_result("'hello'")) == "hello"
assert Pythonx.decode(eval_result("'🦊 in a 🎁'")) == "🦊 in a 🎁"
end
test "bytes" do
assert Pythonx.decode(eval_result(~S"b'A\xff'")) == <<65, 255>>
end
test "list" do
assert Pythonx.decode(eval_result("[]")) == []
assert Pythonx.decode(eval_result("[1, 2.0, 'hello']")) == [1, 2.0, "hello"]
end
test "tuple" do
assert Pythonx.decode(eval_result("()")) == {}
assert Pythonx.decode(eval_result("(1,)")) == {1}
assert Pythonx.decode(eval_result("(1, 2.0, 'hello')")) == {1, 2.0, "hello"}
end
test "map" do
assert Pythonx.decode(eval_result("{'hello': 1}")) == %{"hello" => 1}
assert Pythonx.decode(eval_result("{2: None}")) == %{2 => nil}
end
test "mapset" do
assert Pythonx.decode(eval_result("set({1})")) == MapSet.new([1])
assert Pythonx.decode(eval_result("frozenset({1})")) == MapSet.new([1])
end
test "identity for other objects" do
assert repr(Pythonx.decode(eval_result("complex(1)"))) == "(1+0j)"
end
end
describe "eval/2" do
test "evaluates a single expression" do
assert {result, %{}} = Pythonx.eval("1 + 1", %{})
assert repr(result) == "2"
end
test "evaluates multiple statements" do
assert {result, %{"nums" => nums, "sum" => sum}} =
Pythonx.eval(
"""
nums = [1, 2, 3]
sum = 0
for num in nums:
sum += num
""",
%{}
)
assert result == nil
assert repr(nums) == "[1, 2, 3]"
assert repr(sum) == "6"
end
test "returns the result of last expression" do
assert {result, %{"x" => %Pythonx.Object{}, "y" => %Pythonx.Object{}}} =
Pythonx.eval(
"""
x = 1
y = 1
x + y
""",
%{}
)
assert repr(result) == "2"
end
test "returns nil for empty code" do
assert {result, %{}} = Pythonx.eval("", %{})
assert result == nil
assert {result, %{}} = Pythonx.eval("# Comment", %{})
assert result == nil
end
test "encodes terms given as globals" do
assert {result, %{"x" => x, "y" => y, "z" => z}} =
Pythonx.eval(
"""
z = 3
x + y + z
""",
%{"x" => 1, "y" => 2}
)
assert repr(result) == "6"
assert repr(x) == "1"
assert repr(y) == "2"
assert repr(z) == "3"
end
test "does not leak globals across evaluations" do
assert {_result, globals} = Pythonx.eval("x = 1", %{})
assert Map.keys(globals) == ["x"]
assert {_result, globals} = Pythonx.eval("y = 1", %{})
assert Map.keys(globals) == ["y"]
end
test "propagates exceptions" do
assert_raise Pythonx.Error, ~r/NameError: name 'x' is not defined/, fn ->
Pythonx.eval("x", %{})
end
end
test "with external package" do
# Note that we install numpy in test_helper.exs. It is a good
# integration test to make sure the numpy C extension works
# correctly with the dynamically loaded libpython.
assert {result, %{"np" => %Pythonx.Object{}}} =
Pythonx.eval(
"""
import numpy as np
np.array([1, 2, 3]) * np.array(10)
""",
%{}
)
assert repr(result) == "array([10, 20, 30])"
end
test "sends standard output to caller's group leader" do
assert ExUnit.CaptureIO.capture_io(fn ->
Pythonx.eval(
"""
print("hello from Python")
""",
%{}
)
end) == "hello from Python\n"
# Python thread spawned by the evaluation
assert ExUnit.CaptureIO.capture_io(fn ->
Pythonx.eval(
"""
import threading
def run():
print("hello from thread")
thread = threading.Thread(target=run)
thread.start()
thread.join()
""",
%{}
)
end) == "hello from thread\n"
end
test "sends standard error to caller's group leader" do
assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
Pythonx.eval(
"""
import sys
print("error from Python", file=sys.stderr)
""",
%{}
)
end) =~ "error from Python\n"
end
test "sends standard output and error to custom processes when specified" do
{:ok, io} = StringIO.open("")
Pythonx.eval(
"""
import sys
import threading
print("hello from Python")
print("error from Python", file=sys.stderr)
def run():
print("hello from thread")
thread = threading.Thread(target=run)
thread.start()
thread.join()
""",
%{},
stdout_device: io,
stderr_device: io
)
{:ok, {_, output}} = StringIO.close(io)
assert output =~ "hello from Python"
assert output =~ "error from Python"
assert output =~ "hello from thread"
end
test "raises Python error on stdin attempt" do
assert_raise Pythonx.Error, ~r/RuntimeError: stdin not supported/, fn ->
Pythonx.eval(
"""
input()
""",
%{}
)
end
end
end
describe "sigil_PY/2" do
# Note that we evaluate code so that sigil expansion happens at
# test runtime. This also allows us to control binding precisely.
#
# Tests for different Python constructs are in Pythonx.ASTTest,
# here we only verify the macro behaviour.
test "defines Elixir variables corresponding to newly defined globals" do
{_result, binding} =
Code.eval_string(~S'''
import Pythonx
~PY"""
x = 1
"""
''')
assert [x: %Pythonx.Object{}] = binding
end
test "defines Elixir variables for both conditional branches" do
# Python allows for defining different variables in conditional
# branches, but we need to generate the assignments at compile
# time, so we generate them for all variables. Variables from
# the skipped branches get assigned nil.
{_result, binding} =
Code.eval_string(~S'''
import Pythonx
~PY"""
if True:
x = 1
else:
y = 2
"""
''')
assert %Pythonx.Object{} = binding[:x]
assert binding[:y] == nil
end
test "passes referenced global variables from Elixir binding" do
code =
~S'''
import Pythonx
~PY"""
x + 1
"""
'''
quoted = Code.string_to_quoted!(code)
binding = [x: 1, unused: 1]
env = Code.env_for_eval([])
{_result, binding, _env} =
Code.eval_quoted_with_env(quoted, binding, env, prune_binding: true)
# Verify that :unused was not used (therefore pruned from binding).
assert Keyword.keys(binding) == [:x]
end
test "results in a Python error when a variable is undefined" do
assert_raise Pythonx.Error, ~r/NameError: name 'x' is not defined/, fn ->
Code.eval_string(
~S'''
import Pythonx
~PY"""
x + 1
"""
''',
[]
)
end
end
test "global redefinition" do
{_result, binding} =
Code.eval_string(
~S'''
import Pythonx
~PY"""
x = x + 1
"""
''',
x: 1
)
assert [x: %Pythonx.Object{} = x] = binding
assert repr(x) == "2"
end
test "supports uppercase variables" do
# Uppercase variables cannot be defined directly in Elixir,
# however macros can do that by building AST by hand.
{result, binding} =
Code.eval_string(~S'''
import Pythonx
~PY"""
ANSWER = 42
"""
~PY"""
ANSWER + 1
"""
''')
assert [ANSWER: %Pythonx.Object{}] = binding
assert repr(result) == "43"
end
test "does not result in unused variables diagnostics" do
{_result, diagnostics} =
Code.with_diagnostics(fn ->
Code.eval_string(~s'''
defmodule TestModule#{System.unique_integer([:positive])} do
import Pythonx
def run() do
~PY"""
x = 1
"""
end
end
''')
end)
assert diagnostics == []
end
end
defp repr(object) do
assert %Pythonx.Object{} = object
object
|> Pythonx.NIF.object_repr()
|> Pythonx.NIF.unicode_to_string()
end
defp eval_result(code) do
assert {result, %{}} = Pythonx.eval(code, %{})
result
end
end