github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/tests/stringindex_test.go (about) 1 package tests 2 3 import ( 4 "testing" 5 6 "github.com/madlambda/nash/tests/internal/tester" 7 ) 8 9 func TestStringIndexing(t *testing.T) { 10 tester.Run(t, Nashcmd, 11 tester.TestCase{ 12 Name: "IterateEmpty", 13 ScriptCode: ` 14 var a = "" 15 for x in $a { 16 exit("1") 17 } 18 echo "ok" 19 `, 20 ExpectStdout: "ok\n", 21 }, 22 tester.TestCase{ 23 Name: "IndexEmptyFails", 24 ScriptCode: ` 25 var a = "" 26 echo $a[0] 27 `, 28 Fails: true, 29 ExpectStderrToContain: "IndexError", 30 }, 31 tester.TestCase{ 32 Name: "IsImmutable", 33 ScriptCode: ` 34 var a = "12" 35 a[0] = "2" 36 echo $a 37 `, 38 Fails: true, 39 ExpectStderrToContain: "IndexError", 40 }, 41 ) 42 } 43 func TestStringIndexingASCII(t *testing.T) { 44 tester.Run(t, Nashcmd, 45 tester.TestCase{Name: "PositionalAccess", 46 ScriptCode: ` 47 var a = "12" 48 echo $a[0] 49 echo $a[1] 50 `, 51 ExpectStdout: "1\n2\n", 52 }, 53 tester.TestCase{ 54 Name: "PositionalAccessReturnsString", 55 ScriptCode: ` 56 var a = "12" 57 var x = $a[0] + $a[1] 58 echo $x 59 `, 60 ExpectStdout: "12\n", 61 }, 62 tester.TestCase{ 63 Name: "Len", 64 ScriptCode: ` 65 var a = "12" 66 var l <= len($a) 67 echo $l 68 `, 69 ExpectStdout: "2\n", 70 }, 71 tester.TestCase{ 72 Name: "Iterate", 73 ScriptCode: ` 74 var a = "123" 75 for x in $a { 76 echo $x 77 } 78 `, 79 ExpectStdout: "1\n2\n3\n", 80 }, 81 tester.TestCase{ 82 Name: "IndexOutOfRangeFails", 83 ScriptCode: ` 84 var a = "123" 85 echo $a[3] 86 `, 87 Fails: true, 88 ExpectStderrToContain: "IndexError", 89 }, 90 ) 91 } 92 93 func TestStringIndexingNonASCII(t *testing.T) { 94 tester.Run(t, Nashcmd, 95 tester.TestCase{Name: "PositionalAccess", 96 ScriptCode: ` 97 var a = "⌘⌘" 98 echo $a[0] 99 echo $a[1] 100 `, 101 ExpectStdout: "⌘\n⌘\n", 102 }, 103 tester.TestCase{ 104 Name: "Iterate", 105 ScriptCode: ` 106 var a = "⌘⌘" 107 for x in $a { 108 echo $x 109 } 110 `, 111 ExpectStdout: "⌘\n⌘\n", 112 }, 113 tester.TestCase{ 114 Name: "PositionalAccessReturnsString", 115 ScriptCode: ` 116 var a = "⌘⌘" 117 var x = $a[0] + $a[1] 118 echo $x 119 `, 120 ExpectStdout: "⌘⌘\n", 121 }, 122 tester.TestCase{ 123 Name: "Len", 124 ScriptCode: ` 125 var a = "⌘⌘" 126 var l <= len($a) 127 echo $l 128 `, 129 ExpectStdout: "2\n", 130 }, 131 tester.TestCase{ 132 Name: "IndexOutOfRangeFails", 133 ScriptCode: ` 134 var a = "⌘⌘" 135 echo $a[2] 136 `, 137 Fails: true, 138 ExpectStderrToContain: "IndexError", 139 }, 140 ) 141 }