Debian Codegraph @

extra_tests/hpy_tests/_vendored/test_eval.py

raw symbols SCIP
1 from .support import HPyTest
2
3 class TestEval(HPyTest):
4 def test_compile(self):
5 import pytest
6 from textwrap import dedent
7 mod = self.make_module("""
8 HPyDef_METH(f, "f", HPyFunc_VARARGS)
9 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
10 {
11 const char *source, *filename;
12 HPy_SourceKind src_kind;
13 int src_kind_i;
14 if (!HPyArg_Parse(ctx, NULL, args, nargs, "ssi", &source, &filename, &src_kind_i))
15 return HPy_NULL;
16
17 switch (src_kind_i)
18 {
19 case 0: src_kind = HPy_SourceKind_Expr; break;
20 case 1: src_kind = HPy_SourceKind_File; break;
21 case 2: src_kind = HPy_SourceKind_Single; break;
22 default:
23 // just pass through for testing
24 src_kind = (HPy_SourceKind) src_kind_i;
25 }
26 return HPy_Compile_s(ctx, source, filename, src_kind);
27 }
28 @EXPORT(f)
29 @INIT
30 """)
31 c0 = mod.f("1 + 2", "hello0.py", 0)
32 assert c0
33 assert c0.co_filename == "hello0.py"
34 assert eval(c0) == 3
35
36 c1 = mod.f(dedent("""
37 a = 1
38 b = 2
39 def add(x, y):
40 return x + y
41 res = add(a, b)
42 """), "hello1.py", 1)
43 globals1 = dict()
44 locals1 = dict()
45 assert eval(c1, globals1, locals1) is None
46 assert "add" in locals1, "was: %r" % locals1
47 assert locals1["a"] == 1
48 assert locals1["b"] == 2
49 assert locals1["res"] == 3
50
51 c2 = mod.f("x = 1 + 2", "hello2.py", 2)
52 locals2 = dict()
53 assert eval(c2, dict(), locals2) is None
54 assert locals2["x"] == 3
55
56 with pytest.raises(SyntaxError):
57 mod.f("1 +.", "hello1.c", 0)
58
59 with pytest.raises(SystemError):
60 mod.f("1+2", "hello.c", 777)
61
62 def test_eval_code(self):
63 import pytest
64 mod = self.make_module("""
65 HPyDef_METH(f, "f", HPyFunc_VARARGS)
66 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
67 {
68 if (nargs != 3) {
69 HPyErr_SetString(ctx, ctx->h_TypeError, "expected exactly 3 args");
70 return HPy_NULL;
71 }
72 return HPy_EvalCode(ctx, args[0], args[1], args[2]);
73 }
74 @EXPORT(f)
75 @INIT
76 """)
77 c0 = compile("a + b", "hello.py", "eval")
78 assert mod.f(c0, dict(), dict(a=2, b=3)) == 5
79
80 locals1 = dict(a=10, b=20)
81 c1 = compile("x = a + b", "hello.py", "exec")
82 assert mod.f(c1, dict(), locals1) is None
83 assert locals1['x'] == 30
84
85 c0 = compile("raise ValueError", "hello.py", "exec")
86 with pytest.raises(ValueError):
87 mod.f(c0, dict(__builtins__=__builtins__), dict())