github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/internal/sh/builtin/format_test.go (about) 1 package builtin_test 2 3 import "testing" 4 5 func TestFormat(t *testing.T) { 6 type formatDesc struct { 7 script string 8 output string 9 } 10 11 tests := map[string]formatDesc{ 12 "textonly": { 13 script: ` 14 var r <= format("helloworld") 15 echo $r 16 `, 17 output: "helloworld\n", 18 }, 19 "ncallsRegressionTest": { 20 script: ` 21 fn formatstuff() { 22 var r <= format("hello%s", "world") 23 echo $r 24 } 25 formatstuff() 26 formatstuff() 27 `, 28 output: "helloworld\nhelloworld\n", 29 }, 30 "ncallsWithVarsRegressionTest": { 31 script: ` 32 fn formatstuff() { 33 var b = "world" 34 var r <= format("hello%s", $b) 35 var s <= format("hackthe%s", $b) 36 echo $r 37 echo $s 38 } 39 formatstuff() 40 formatstuff() 41 `, 42 output: "helloworld\nhacktheworld\nhelloworld\nhacktheworld\n", 43 }, 44 "fmtstring": { 45 script: ` 46 var r <= format("%s:%s", "hello", "world") 47 echo $r 48 `, 49 output: "hello:world\n", 50 }, 51 "fmtlist": { 52 script: ` 53 var list = ("1" "2" "3") 54 var r <= format("%s:%s", "list", $list) 55 echo $r 56 `, 57 output: "list:1 2 3\n", 58 }, 59 "funconly": { 60 script: ` 61 fn func() {} 62 var r <= format($func) 63 echo $r 64 `, 65 output: "<fn func>\n", 66 }, 67 "funcfmt": { 68 script: ` 69 fn func() {} 70 var r <= format("calling:%s", $func) 71 echo $r 72 `, 73 output: "calling:<fn func>\n", 74 }, 75 "listonly": { 76 script: ` 77 var list = ("1" "2" "3") 78 var r <= format($list) 79 echo $r 80 `, 81 output: "1 2 3\n", 82 }, 83 "listoflists": { 84 script: ` 85 var list = (("1" "2" "3") ("4" "5" "6")) 86 var r <= format("%s:%s", "listoflists", $list) 87 echo $r 88 `, 89 output: "listoflists:1 2 3 4 5 6\n", 90 }, 91 "listasfmt": { 92 script: ` 93 var list = ("%s" "%s") 94 var r <= format($list, "1", "2") 95 echo $r 96 `, 97 output: "1 2\n", 98 }, 99 "invalidFmt": { 100 script: ` 101 var r <= format("%d%s", "invalid") 102 echo $r 103 `, 104 output: "%!d(string=invalid)%!s(MISSING)\n", 105 }, 106 } 107 108 for name, desc := range tests { 109 t.Run(name, func(t *testing.T) { 110 output := execSuccess(t, desc.script) 111 if output != desc.output { 112 t.Fatalf("got %q expected %q", output, desc.output) 113 } 114 }) 115 } 116 } 117 118 func TestFormatfErrors(t *testing.T) { 119 type formatDesc struct { 120 script string 121 } 122 123 tests := map[string]formatDesc{ 124 "noParams": {script: `format()`}, 125 } 126 127 for name, desc := range tests { 128 t.Run(name, func(t *testing.T) { 129 execFailure(t, desc.script) 130 }) 131 } 132 }