src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/parse/quote_test.go (about) 1 package parse 2 3 import ( 4 "testing" 5 6 "src.elv.sh/pkg/tt" 7 ) 8 9 func TestQuote(t *testing.T) { 10 tt.Test(t, tt.Fn(Quote).ArgsFmt("(%q)"), 11 // Empty string is single-quoted. 12 Args("").Rets(`''`), 13 14 // Bareword when possible. 15 Args("x-y:z@h/d").Rets("x-y:z@h/d"), 16 17 // Single quote when there are special characters but no unprintable 18 // characters. 19 Args("x$y[]ef'").Rets("'x$y[]ef'''"), 20 21 // Tilde needs quoting only leading the expression. 22 Args("~x").Rets("'~x'"), 23 Args("x~").Rets("x~"), 24 25 // Double quote when there is unprintable char. 26 Args("a\nb").Rets(`"a\nb"`), 27 Args("\x1b\"\\").Rets(`"\e\"\\"`), 28 Args("\x00").Rets(`"\x00"`), 29 Args("\x7f").Rets(`"\x7f"`), 30 Args("\u0090").Rets(`"\u0090"`), 31 Args("\u0600").Rets(`"\u0600"`), // Arabic number sign 32 Args("\ufffd").Rets(`"\ufffd"`), // Unicode replacement character 33 Args("\U000110BD").Rets(`"\U000110bd"`), // Kathi number sign 34 35 // String containing characters that can be single-quoted are 36 // double-quoted when it also contains unprintable characters. 37 Args("$\n").Rets(`"$\n"`), 38 39 // Commas and equal signs are always quoted, so that the quoted string is 40 // safe for use everywhere. 41 Args("a,b").Rets(`'a,b'`), 42 Args("a=b").Rets(`'a=b'`), 43 44 // Double quote strings containing invalid UTF-8 sequences with \x. 45 Args("bad\xffUTF-8").Rets(`"bad\xffUTF-8"`), 46 ) 47 } 48 49 func TestQuoteAs(t *testing.T) { 50 tt.Test(t, tt.Fn(QuoteAs).ArgsFmt("(%q, %s)"), 51 // DoubleQuote is always respected. 52 Args("", DoubleQuoted).Rets(`""`, DoubleQuoted), 53 Args("a", DoubleQuoted).Rets(`"a"`, DoubleQuoted), 54 55 // SingleQuoted is respected when there is no unprintable character. 56 Args("", SingleQuoted).Rets(`''`, SingleQuoted), 57 Args("a", SingleQuoted).Rets(`'a'`, SingleQuoted), 58 Args("\n", SingleQuoted).Rets(`"\n"`, DoubleQuoted), 59 60 // Bareword tested above in TestQuote. 61 ) 62 } 63 64 func TestQuoteVariableName(t *testing.T) { 65 tt.Test(t, tt.Fn(QuoteVariableName).ArgsFmt("(%q)"), 66 Args("").Rets("''"), 67 Args("foo").Rets("foo"), 68 Args("a/b").Rets("'a/b'"), 69 Args("\x1b").Rets(`"\e"`), 70 Args("bad\xffUTF-8").Rets(`"bad\xffUTF-8"`), 71 Args("$\n").Rets(`"$\n"`), 72 ) 73 } 74 75 func TestQuoteCommandName(t *testing.T) { 76 tt.Test(t, tt.Fn(QuoteCommandName).ArgsFmt("(%q)"), 77 Args("<").Rets("<"), 78 Args("foo").Rets("foo"), 79 Args("$").Rets(`'$'`), 80 ) 81 }