OILS / spec / ysh-object.test.sh View on Github | oilshell.org

158 lines, 68 significant
1## our_shell: ysh
2## oils_failures_allowed: 3
3
4#### Object() creates prototype chain
5
6func Rect_area(this) {
7 return (this.x * this.y)
8}
9
10var Rect = Object(null, {area: Rect_area})
11
12var rect1 = Object(Rect, {x: 3, y: 4})
13var rect2 = Object(Rect, {x: 10, y: 20})
14
15# This could change to show the object?
16# pp test_ (rect)
17
18# TODO: This should be a bound function
19#pp asdl_ (rect)
20#pp (rect.area)
21#pp (rect->area)
22
23var area1 = rect1.area()
24var area2 = rect2.area()
25
26pp test_ ([rect1.x, rect1.y])
27echo "area1 = $area1"
28
29pp test_ ([rect2.x, rect2.y])
30echo "area2 = $area2"
31
32#pp test_ (rect1.nonexistent)
33
34## STDOUT:
35(List) [3,4]
36area1 = 12
37(List) [10,20]
38area2 = 200
39## END
40
41#### prototype()
42
43func Rect_area(this) {
44 return (this.x * this.y)
45}
46
47var Rect = Object(null, {area: Rect_area})
48
49var obj = Object(Rect, {x: 3, y: 4})
50
51pp test_ (prototype(Rect))
52pp test_ (prototype(obj))
53
54## STDOUT:
55## END
56
57#### Copy to Dict with dict(), and mutate
58
59var rect = Object(null, {x: 3, y: 4})
60var d = dict(rect)
61
62pp test_ (rect)
63pp test_ (d)
64
65# Right now, object attributes aren't mutable! Could change this.
66#
67setvar rect.x = 99
68setvar d.x = 100
69
70pp test_ (rect)
71pp test_ (d)
72## STDOUT:
73(Obj) {"x":3,"y":4}
74(Dict) {"x":3,"y":4}
75(Obj) {"x":99,"y":4}
76(Dict) {"x":100,"y":4}
77## END
78
79#### setvar obj.attr = and += and ...
80
81var rect = Object(null, {x: 3, y: 4})
82pp test_ (rect)
83
84setvar rect.y = 99
85pp test_ (rect)
86
87setvar rect.y += 3
88pp test_ (rect)
89
90setvar rect.x *= 5
91pp test_ (rect)
92
93## STDOUT:
94(Obj) {"x":3,"y":4}
95(Obj) {"x":3,"y":99}
96(Obj) {"x":3,"y":102}
97(Obj) {"x":15,"y":102}
98## END
99
100#### can't encode objects as JSON
101
102var Rect = Object(null, {})
103
104json write (Rect)
105echo 'nope'
106
107## status: 1
108## STDOUT:
109## END
110
111#### pretty printing of cycles
112
113var d = {k: 42}
114setvar d.cycle = d
115
116pp test_ (d)
117
118var o = Object(null, d)
119
120pp test_ (o)
121
122var o2 = Object(o, {z: 99})
123
124pp test_ (o2)
125
126## STDOUT:
127## END
128
129#### Can all builtin methods with s.upper()
130
131var s = 'foo'
132var x = s.upper()
133var y = "--$[x.lower()]"
134
135pp test_ (x)
136pp test_ (y)
137
138## STDOUT:
139(Str) "FOO"
140(Str) "--foo"
141## END
142
143
144#### Dict.keys(d), Dict.values(d), Dict.get(d, key)
145
146var d = {a: 42, b: 99}
147
148pp test_ (Dict.keys(d))
149pp test_ (Dict.values(d))
150
151pp test_ (Dict.get(d, 'key', 'default'))
152
153# mutating methods are OK?
154# call d->inc(x)
155
156## STDOUT:
157## END
158