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

605 lines, 372 significant
1# spec/ysh-methods
2
3## our_shell: ysh
4## oils_failures_allowed: 2
5
6#### => operator for pure computation is allowed (may be mandatory later)
7
8# later we may make it mandatory
9
10if ("abc" => startsWith("a")) {
11 echo yes
12}
13
14var mylist = [1, 2, 3]
15
16# This one should be ->
17call mylist->pop()
18echo 'ok'
19
20## STDOUT:
21yes
22ok
23## END
24
25#### => can be used to chain free functions
26
27func dictfunc() {
28 return ({k1: 'spam', k2: 'eggs'})
29}
30
31echo $[list(dictfunc()) => join('/') => upper()]
32
33# This is nicer and more consistent
34echo $[dictfunc() => list() => join('/') => upper()]
35
36## STDOUT:
37K1/K2
38K1/K2
39## END
40
41#### Str => startsWith(Str) and endsWith(Str), simple
42func test(s, p) { echo $[s => startsWith(p)] $[s => endsWith(p)] }
43
44call test('', '')
45call test('abc', '')
46call test('abc', 'a')
47call test('abc', 'b')
48call test('abc', 'c')
49call test('abc', 'z')
50call test('', 'abc')
51## status: 0
52## STDOUT:
53true true
54true true
55true false
56false false
57false true
58false false
59false false
60## END
61
62#### Str => startsWith(Str) and endsWith(Str), matches bytes not runes
63func test(s, p) { echo $[s => startsWith(p)] $[s => endsWith(p)] }
64
65call test(b'\yce\ya3', u'\u{03a3}')
66call test(b'\yce\ya3', b'\yce')
67call test(b'\yce\ya3', b'\ya3')
68call test(b'\yce', b'\yce')
69## status: 0
70## STDOUT:
71true true
72true false
73false true
74true true
75## END
76
77#### Str => startsWith(Str) and endsWith(Str), eggex
78func test(s, p) { echo $[s => startsWith(p)] $[s => endsWith(p)] }
79
80call test('abc', / d+ /)
81call test('abc', / [ a b c ] /)
82call test('abc', / 'abc' /)
83call test('cba', / d+ /)
84call test('cba', / [ a b c ] /)
85call test('cba', / 'abc' /)
86## status: 0
87## STDOUT:
88false false
89true true
90true true
91false false
92true true
93false false
94## END
95
96#### Str => startsWith(Str) and endsWith(Str), eggex with anchors
97func test(s, p) { echo $[s => startsWith(p)] $[s => endsWith(p)] }
98
99call test('ab', / %start 'a' /)
100call test('ab', / 'a' %end /)
101call test('ab', / %start 'a' %end /)
102call test('ab', / %start 'b' /)
103call test('ab', / 'b' %end /)
104call test('ab', / %start 'b' %end /)
105## status: 0
106## STDOUT:
107true false
108false false
109false false
110false false
111false true
112false false
113## END
114
115#### Str => startsWith(Str) and endsWith(Str), eggex matches bytes not runes
116func test(s, p) { echo $[s => startsWith(p)] $[s => endsWith(p)] }
117
118call test(u'\u{03a3}', / dot /)
119call test(u'\u{03a3}', / ![z] /)
120call test(b'\yce', / dot /) # Fails: eggex does not match bytes
121call test(b'\yce', / ![z] /) # Fails: eggex does not match bytes
122## status: 0
123## STDOUT:
124true true
125true true
126true true
127true true
128## END
129
130#### Str => startsWith(), no args
131= 'abc' => startsWith()
132## status: 3
133
134#### Str => startsWith(), too many args
135= 'abc' => startsWith('extra', 'arg')
136## status: 3
137
138#### Str => endsWith(), no args
139= 'abc' => endsWith()
140## status: 3
141
142#### Str => endsWith(), too many args
143= 'abc' => endsWith('extra', 'arg')
144## status: 3
145
146#### Str => trim*() with no args trims whitespace
147func test(s) { write --sep ', ' --j8 $[s => trimStart()] $[s => trimEnd()] $[s => trim()] }
148
149call test("")
150call test(" ")
151call test("mystr")
152call test(" mystr")
153call test("mystr ")
154call test(" mystr ")
155call test(" my str ")
156## status: 0
157## STDOUT:
158"", "", ""
159"", "", ""
160"mystr", "mystr", "mystr"
161"mystr", " mystr", "mystr"
162"mystr ", "mystr", "mystr"
163"mystr ", " mystr", "mystr"
164"my str ", " my str", "my str"
165## END
166
167#### Str => trim*() with a simple string pattern trims pattern
168func test(s, p) { write --sep ', ' --j8 $[s => trimStart(p)] $[s => trimEnd(p)] $[s => trim(p)] }
169
170call test('' , 'xyz')
171call test(' ' , 'xyz')
172call test('xy' , 'xyz')
173call test('yz' , 'xyz')
174call test('xyz' , 'xyz')
175call test('xyzxyz' , 'xyz')
176call test('xyzxyzxyz', 'xyz')
177## status: 0
178## STDOUT:
179"", "", ""
180" ", " ", " "
181"xy", "xy", "xy"
182"yz", "yz", "yz"
183"", "", ""
184"xyz", "xyz", ""
185"xyzxyz", "xyzxyz", "xyz"
186## END
187
188#### Str => trim*() with a string pattern trims bytes not runes
189func test(s, p) { write --sep ', ' --j8 $[s => trimStart(p)] $[s => trimEnd(p)] $[s => trim(p)] }
190
191call test(b'\yce\ya3', u'\u{03a3}')
192call test(b'\yce\ya3', b'\yce')
193call test(b'\yce\ya3', b'\ya3')
194## status: 0
195## STDOUT:
196"", "", ""
197b'\ya3', "Σ", b'\ya3'
198"Σ", b'\yce', b'\yce'
199## END
200
201#### Str => trim*() with an eggex pattern trims pattern
202func test(s, p) { write --sep ', ' --j8 $[s => trimStart(p)] $[s => trimEnd(p)] $[s => trim(p)] }
203
204call test('' , / 'xyz' /)
205call test(' ' , / 'xyz' /)
206call test('xy' , / 'xyz' /)
207call test('yz' , / 'xyz' /)
208call test('xyz' , / 'xyz' /)
209call test('xyzxyz' , / 'xyz' /)
210call test('xyzxyzxyz', / 'xyz' /)
211call test('xyzabcxyz', / 'xyz' /)
212call test('xyzabcxyz', / %start 'xyz' /)
213call test('xyzabcxyz', / 'xyz' %end /)
214call test('123abc123', / d+ /)
215## status: 0
216## STDOUT:
217"", "", ""
218" ", " ", " "
219"xy", "xy", "xy"
220"yz", "yz", "yz"
221"", "", ""
222"xyz", "xyz", ""
223"xyzxyz", "xyzxyz", "xyz"
224"abcxyz", "xyzabc", "abc"
225"abcxyz", "xyzabcxyz", "abcxyz"
226"xyzabcxyz", "xyzabc", "xyzabc"
227"abc123", "123abc", "abc"
228## END
229
230#### Str => trim*() with an eggex pattern trims bytes not runes
231func test(s, p) { write --sep ', ' --j8 $[s => trimStart(p)] $[s => trimEnd(p)] $[s => trim(p)] }
232
233call test(u'\u{03a3}', / dot /) # Fails: eggex does not match bytes, so entire rune is trimmed.
234call test(u'\u{03a3}', / ![z] /) # Fails: eggex does not match bytes, so entire rune is trimmed.
235call test(b'\yce', / dot /) # Fails: eggex does not match bytes, so nothing is trimmed.
236call test(b'\yce', / ![z] /) # Fails: eggex does not match bytes, so nothing is trimmed.
237## status: 0
238## STDOUT:
239b'\ya3', b'\yce', ""
240b'\ya3', b'\yce', ""
241"", "", ""
242"", "", ""
243## END
244
245#### Str => trim(), too many args
246= 'mystr' => trim('extra', 'args')
247## status: 3
248
249#### Str => trimStart(), too many args
250= 'mystr' => trimStart('extra', 'args')
251## status: 3
252
253#### Str => trimEnd(), too many args
254= 'mystr' => trimEnd('extra', 'args')
255## status: 3
256
257#### Str => trim(), unicode whitespace aware
258
259# Supported set of whitespace characters. The full set of Unicode whitespace
260# characters is not supported. See comments in the implementation.
261var spaces = [
262 b'\u{0009}', # Horizontal tab (\t)
263 b'\u{000A}', # Newline (\n)
264 b'\u{000B}', # Vertical tab (\v)
265 b'\u{000C}', # Form feed (\f)
266 b'\u{000D}', # Carriage return (\r)
267 b'\u{0020}', # Normal space
268 b'\u{00A0}', # No-break space <NBSP>
269 b'\u{FEFF}', # Zero-width no-break space <ZWNBSP>
270] => join('')
271
272echo $["$spaces YSH $spaces" => trim()]
273## status: 0
274## STDOUT:
275YSH
276## END
277
278#### Str => trim*(), unicode decoding errors
279var badUtf = b'\yF9'
280
281echo trim
282
283# We only decode UTF until the first non-space char. So the bad UTF-8 is
284# missed.
285try { call " a$[badUtf]b " => trim() }
286echo status=$_status
287
288# These require trim to decode the badUtf, so an error is raised
289try { call "$[badUtf]b " => trim() }
290echo status=$_status
291try { call " a$[badUtf]" => trim() }
292echo status=$_status
293
294# Similarly, trim{Left,Right} will assume correct encoding until shown
295# otherwise.
296echo trimStart
297try { call " a$[badUtf]" => trimStart() }
298echo status=$_status
299try { call "$[badUtf]b " => trimStart() }
300echo status=$_status
301
302echo trimEnd
303try { call "$[badUtf]b " => trimEnd() }
304echo status=$_status
305try { call " a$[badUtf]" => trimEnd() }
306echo status=$_status
307
308## STDOUT:
309trim
310status=0
311status=3
312status=3
313trimStart
314status=0
315status=3
316trimEnd
317status=0
318status=3
319## END
320
321#### Str => trimStart(), unicode decoding error types
322var badStrs = [
323 b'\yF4\yA2\yA4\yB0', # Too large of a codepoint
324 b'\yED\yBF\y80', # Surrogate
325 b'\yC1\y81', # Overlong
326 b'\y80', b'\yFF', # Does not match UTF8 bit pattern
327]
328
329for badStr in (badStrs) {
330 try { call badStr => trimStart() }
331 echo status=$_status
332}
333
334## STDOUT:
335status=3
336status=3
337status=3
338status=3
339status=3
340## END
341
342#### Str => trimEnd(), unicode decoding error types
343# Tests the backwards UTF-8 decoder
344var badStrs = [
345 b'\yF4\yA2\yA4\yB0', # Too large of a codepoint
346 b'\yED\yBF\y80', # Surrogate
347 b'\yC1\y81', # Overlong
348 b'\y80', b'\yFF', # Does not match UTF8 bit pattern
349]
350
351for badStr in (badStrs) {
352 try { call badStr => trimEnd() }
353 echo status=$_status
354}
355
356## STDOUT:
357status=3
358status=3
359status=3
360status=3
361status=3
362## END
363
364#### Str => trim*(), zero-codepoints are not NUL-terminators
365json write (b' \y00 ' => trim())
366json write (b' \y00 ' => trimStart())
367json write (b' \y00 ' => trimEnd())
368## STDOUT:
369"\u0000"
370"\u0000 "
371" \u0000"
372## END
373
374#### Dict => keys()
375var en2fr = {}
376setvar en2fr["hello"] = "bonjour"
377setvar en2fr["friend"] = "ami"
378setvar en2fr["cat"] = "chat"
379pp test_ (en2fr => keys())
380## status: 0
381## STDOUT:
382(List) ["hello","friend","cat"]
383## END
384
385#### Str => split(sep), non-empty str sep
386pp test_ ('a,b,c'.split(','))
387pp test_ ('aa'.split('a'))
388pp test_ ('a<>b<>c<d'.split('<>'))
389pp test_ ('a;b;;c'.split(';'))
390pp test_ (''.split('foo'))
391## STDOUT:
392(List) ["a","b","c"]
393(List) ["","",""]
394(List) ["a","b","c<d"]
395(List) ["a","b","","c"]
396(List) []
397## END
398
399#### Str => split(sep), eggex sep
400pp test_ ('a,b;c'.split(/ ',' | ';' /))
401pp test_ ('aa'.split(/ dot* /))
402pp test_ ('aa'.split(/ dot /))
403pp test_ ('a<>b@@c<d'.split(/ '<>' | '@@' /))
404pp test_ ('a b cd'.split(/ space* /))
405pp test_ ('a b cd'.split(/ space+ /))
406pp test_ (''.split(/ dot /))
407## STDOUT:
408(List) ["a","b","c"]
409(List) ["",""]
410(List) ["","",""]
411(List) ["a","b","c<d"]
412(List) ["a","b","cd"]
413(List) ["a","b","cd"]
414(List) []
415## END
416
417#### Str => split(sep, count), non-empty str sep
418pp test_ ('a,b,c'.split(',', count=-1))
419pp test_ ('a,b,c'.split(',', count=-2)) # Any negative count means "ignore count"
420pp test_ ('aa'.split('a', count=1))
421pp test_ ('a<>b<>c<d'.split('<>', count=10))
422pp test_ ('a;b;;c'.split(';', count=2))
423pp test_ (''.split('foo', count=3))
424pp test_ ('a,b,c'.split(',', count=0))
425pp test_ (''.split(',', count=0))
426## STDOUT:
427(List) ["a","b","c"]
428(List) ["a","b","c"]
429(List) ["","a"]
430(List) ["a","b","c<d"]
431(List) ["a","b",";c"]
432(List) []
433(List) ["a,b,c"]
434(List) []
435## END
436
437#### Str => split(sep, count), eggex sep
438pp test_ ('a,b;c'.split(/ ',' | ';' /, count=-1))
439pp test_ ('aa'.split(/ dot* /, count=1))
440pp test_ ('aa'.split(/ dot /, count=1))
441pp test_ ('a<>b@@c<d'.split(/ '<>' | '@@' /, count=50))
442pp test_ ('a b c'.split(/ space* /, count=0))
443pp test_ ('a b c'.split(/ space+ /, count=0))
444pp test_ (''.split(/ dot /, count=1))
445## STDOUT:
446(List) ["a","b","c"]
447(List) ["",""]
448(List) ["","a"]
449(List) ["a","b","c<d"]
450(List) ["a b c"]
451(List) ["a b c"]
452(List) []
453## END
454
455#### Str => split(), usage errors
456try { pp test_ ('abc'.split('')) } # Sep cannot be ""
457echo status=$[_error.code]
458try { pp test_ ('abc'.split()) } # Sep must be present
459echo status=$[_error.code]
460## STDOUT:
461status=3
462status=3
463## END
464
465#### Str => split(), non-ascii
466pp test_ ('🌞🌝🌞🌝🌞'.split('🌝'))
467pp test_ ('🌞🌝🌞🌝🌞'.split(/ '🌝' /))
468pp test_ ('🌞 🌞 🌝🌞'.split(/ space* /))
469## STDOUT:
470(List) ["🌞","🌞","🌞"]
471(List) ["🌞","🌞","🌞"]
472(List) ["🌞","🌞","🌝🌞"]
473## END
474
475#### Dict => values()
476var en2fr = {}
477setvar en2fr["hello"] = "bonjour"
478setvar en2fr["friend"] = "ami"
479setvar en2fr["cat"] = "chat"
480pp test_ (en2fr => values())
481## status: 0
482## STDOUT:
483(List) ["bonjour","ami","chat"]
484## END
485
486#### Dict -> erase()
487var book = {title: "The Histories", author: "Herodotus"}
488call book->erase("author")
489pp test_ (book)
490# confirm method is idempotent
491call book->erase("author")
492pp test_ (book)
493## status: 0
494## STDOUT:
495(Dict) {"title":"The Histories"}
496(Dict) {"title":"The Histories"}
497## END
498
499#### Dict -> get()
500var book = {title: "Hitchhiker's Guide", published: 1979}
501pp test_ (book => get("title", ""))
502pp test_ (book => get("published", 0))
503pp test_ (book => get("author", ""))
504## status: 0
505## STDOUT:
506(Str) "Hitchhiker's Guide"
507(Int) 1979
508(Str) ""
509## END
510
511#### Separation of -> attr and () calling
512const check = "abc" => startsWith
513pp test_ (check("a"))
514## status: 0
515## STDOUT:
516(Bool) true
517## END
518
519#### Bound methods, receiver value/reference semantics
520var is_a_ref = { "foo": "bar" }
521const f = is_a_ref => keys
522pp test_ (f())
523setvar is_a_ref["baz"] = 42
524pp test_ (f())
525
526var is_a_val = "abc"
527const g = is_a_val => startsWith
528pp test_ (g("a"))
529setvar is_a_val = "xyz"
530pp test_ (g("a"))
531## status: 0
532## STDOUT:
533(List) ["foo"]
534(List) ["foo","baz"]
535(Bool) true
536(Bool) true
537## END
538
539#### List => indexOf()
540var items = [1, '2', 3, { 'a': 5 }]
541
542json write (items => indexOf('a'))
543json write (items => indexOf(1))
544json write (items => indexOf('2'))
545json write (items => indexOf({'a': 5}))
546## STDOUT:
547-1
5480
5491
5503
551## END
552
553#### List => join()
554var items = [1, 2, 3]
555
556json write (items => join()) # default separator is ''
557json write (items => join(" ")) # explicit separator (can be any number or chars)
558json write (items => join(", ")) # separator can be any number of chars
559
560try {
561 json write (items => join(1)) # separator must be a string
562}
563echo "failed with status $_status"
564## STDOUT:
565"123"
566"1 2 3"
567"1, 2, 3"
568failed with status 3
569## END
570
571#### List->reverse()
572
573var empty = []
574
575var a = [0]
576var b = [2, 1, 3]
577var c = :| hello world |
578
579call empty->reverse()
580call a->reverse()
581call b->reverse()
582call c->reverse()
583
584pp test_ (empty)
585pp test_ (a)
586pp test_ (b)
587pp test_ (c)
588
589## STDOUT:
590(List) []
591(List) [0]
592(List) [3,1,2]
593(List) ["world","hello"]
594## END
595
596#### List->reverse() from iterator
597var x = list(0 .. 3)
598call x->reverse()
599write @x
600## STDOUT:
6012
6021
6030
604## END
605