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
722 lines (580 loc) · 18.6 KB
/
Copy pathpythonx_test.exs
File metadata and controls
722 lines (580 loc) · 18.6 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
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 "pid" do
assert repr(Pythonx.encode!(IEx.Helpers.pid(0, 1, 2))) == "<pythonx.PID>"
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 "pid" do
pid = IEx.Helpers.pid(0, 1, 2)
assert {result, %{}} = Pythonx.eval("pid", %{"pid" => pid})
assert Pythonx.decode(result) == pid
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
describe "python API" do
test "pythonx.send sends message to the given pid" do
pid = self()
assert {_result, %{}} =
Pythonx.eval(
"""
import pythonx
pythonx.send_tagged_object(pid, "message_from_python", ("hello", 1))
""",
%{"pid" => pid}
)
assert_receive {:message_from_python, %Pythonx.Object{} = object}
assert repr(object) == "('hello', 1)"
end
end
describe "remote evaluation" do
@describetag :distributed
test "remote_eval/4 returns remote objects" do
{result, globals} =
Pythonx.remote_eval(
@peer1,
"""
x = 1
x
""",
%{}
)
assert inspect(result) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
assert inspect(globals["x"]) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
# Hidden node.
{result, globals} =
Pythonx.remote_eval(
@peer2,
"""
x = 1
x
""",
%{}
)
assert inspect(result) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
assert inspect(globals["x"]) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
end
test "garbage collects only once the caller has no reference to the object" do
{py_test_object, %{}} =
Pythonx.remote_eval(
@peer1,
"""
import os
os.environ["TEST_OBJECT_DELETED"] = "false"
class TestObject:
def call_me(self):
return "maybe"
def __del__(self):
os.environ["TEST_OBJECT_DELETED"] = "true"
TestObject()
""",
%{}
)
:erpc.call(@peer1, :erlang, :garbage_collect, [])
# Can pass the object to another evaluation.
{result, %{}} =
Pythonx.remote_eval(
@peer1,
"""
test_object.call_me()
""",
%{"test_object" => py_test_object}
)
assert inspect(result) =~ "maybe"
Pythonx.remote_eval(@peer1, "import gc; gc.collect()", %{})
{result, %{}} =
Pythonx.remote_eval(@peer1, "import os; os.environ['TEST_OBJECT_DELETED']", %{})
assert inspect(result) =~ "false"
# Hold a reference up until this point.
List.flatten([py_test_object])
:erlang.garbage_collect(self())
Pythonx.remote_eval(@peer1, "import gc; gc.collect()", %{})
# Now it should be garbage collected.
{result, %{}} =
Pythonx.remote_eval(@peer1, "import os; os.environ['TEST_OBJECT_DELETED']", %{})
assert inspect(result) =~ "true"
end
test "remote_eval/4 sends standard output to caller's group leader" do
assert ExUnit.CaptureIO.capture_io(fn ->
Pythonx.remote_eval(
@peer1,
"""
print("hello from Python")
""",
%{}
)
end) == "hello from Python\n"
# Python thread spawned by the evaluation
assert ExUnit.CaptureIO.capture_io(fn ->
Pythonx.remote_eval(
@peer1,
"""
import threading
def run():
print("hello from thread")
thread = threading.Thread(target=run)
thread.start()
thread.join()
""",
%{}
)
end) == "hello from thread\n"
end
test "remote_eval/4 automatically copies objects in globals into the remote node" do
{one, %{}} = Pythonx.eval("1", %{})
{result, globals} = Pythonx.remote_eval(@peer1, "one + 2", %{"one" => one})
assert inspect(result) == """
#Pythonx.Object<
[node: [email protected]]
3
>\
"""
assert inspect(globals["one"]) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
end
test "copy_remote_object/1 makes a local copy of a remote object" do
{result, %{}} = Pythonx.remote_eval(@peer1, "1", %{})
assert inspect(result) == """
#Pythonx.Object<
[node: [email protected]]
1
>\
"""
local = Pythonx.copy_remote_object(result)
assert inspect(local) == """
#Pythonx.Object<
1
>\
"""
end
test "copy_remote_object/1 uses cloudpickle if available" do
# The built-in pickle module does not support lambdas, but cloudpickle does.
{square_it, %{}} = Pythonx.remote_eval(@peer1, "lambda x: x * x", %{})
{result, %{}} =
Pythonx.eval("square_it(2)", %{"square_it" => Pythonx.copy_remote_object(square_it)})
assert repr(result) == "4"
end
test "copy_remote_object/1 keeps already local object as is" do
{result, %{}} = Pythonx.eval("1", %{})
assert Pythonx.copy_remote_object(result) == result
end
test "encode!/1 fails for remote objects" do
{result, %{}} = Pythonx.remote_eval(@peer1, "1", %{})
assert_raise Protocol.UndefinedError, ~r/remote objects cannot be encoded implicitly/, fn ->
Pythonx.encode!(result)
end
end
test "FLAME.Trackable.track/3 pid terminates once there are no more object references" do
{untracked_object, _binding} =
:erpc.call(@peer1, Code, :eval_quoted, [
quote do
{result, %{}} = Pythonx.eval("1", %{})
# Keep the object around, since we track it only later.
Agent.start(fn -> result end)
result
end
])
{tracked_object, [pid]} = FLAME.Trackable.track(untracked_object, [], @peer1)
ref = Process.monitor(pid)
assert :erpc.call(@peer1, Process, :alive?, [pid])
# Hold a reference up until this point.
List.flatten([tracked_object])
:erlang.garbage_collect(self())
assert_receive {:DOWN, ^ref, _, _, _}
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