Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/test/imports.py
1396 views
1
# globals:test_path, GLOBAL_SYMBOL, assrt
2
from _import_one import toplevel_var, toplevel_func as tf, TopLevel, true_var, false_var, test_other
3
from _import_two import (toplevel_var2,
4
toplevel_func2, TopLevel2 as TL2)
5
6
def AClass(x):
7
return this
8
9
eq = assrt.equal
10
# Test import of top-level variables and callables
11
eq(toplevel_var, 'foo')
12
eq(tf('x'), 'xtoplevel')
13
eq(toplevel_var2, 'foo2')
14
eq(toplevel_func2('x'), 'xtoplevel2')
15
eq(false_var, undefined)
16
eq(test_other, 'other')
17
18
# Test import of top-level vars in a conditional
19
eq('true', true_var)
20
21
# Test plain imports
22
import _import_one
23
eq(_import_one.toplevel_var, toplevel_var)
24
eq(_import_one.toplevel_func('x'), tf('x'))
25
26
# Test recognition of imported classes
27
tl = TopLevel('1')
28
eq(tl.a, '1')
29
tl2 = TL2('x')
30
eq(tl2.a, 'x')
31
32
# Test access to submodules via plain imports
33
import _import_two.sub, _import_two.sub as ts
34
eq('sub', _import_two.sub.sub_var)
35
eq('sub', ts.sub_var)
36
eq('sub', _import_two.sub.sub_func())
37
38
# Test deep import
39
from _import_two.level2.deep import deep_var
40
eq('deep', deep_var)
41
42
# Test that class accessed via plain import is
43
# recognized
44
s = _import_two.sub.Sub(1)
45
eq(s.a, 1)
46
s2 = ts.Sub(1)
47
eq(s2.a, 1)
48
49
50
# Test that a class imported into an inner scope is not recognized as a class
51
# outside that scope
52
def inner():
53
from _import_one import AClass
54
a = AClass(1)
55
eq(a.a, 1)
56
57
inner()
58
b = AClass(1)
59
eq(b, this)
60
61
# Test global symbol declared in other module
62
eq(GLOBAL_SYMBOL, 'i am global')
63
64
# Import errors happen during parsing, so we cannot test them directly as they would
65
# prevent this file from being parsed.
66
67
assrt.throws(def():
68
PyLang.parse('from _import_one import not_exported', {'basedir':test_path}).body[0]
69
, /not exported/)
70
assrt.throws(def():
71
PyLang.parse('import xxxx', {'basedir':test_path}).body[0]
72
, /doesn't exist/)
73
74