| 1 | package cmdenv |
| 2 | |
| 3 | import ( |
| 4 | "strconv" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | func TestEscNonPrint(t *testing.T) { |
| 9 | b := []byte("hello") |
| 10 | b[2] = 0x7f |
| 11 | s := string(b) |
| 12 | if !needEscape(s) { |
| 13 | t.Fatal("string needs escaping") |
| 14 | } |
| 15 | if !hasNonPrintable(s) { |
| 16 | t.Fatal("expected non-printable") |
| 17 | } |
| 18 | if hasNonPrintable(EscNonPrint(s)) { |
| 19 | t.Fatal("escaped string has non-printable") |
| 20 | } |
| 21 | if EscNonPrint(`hel\lo`) != `hel\\lo` { |
| 22 | t.Fatal("backslash not escaped") |
| 23 | } |
| 24 | |
| 25 | s = `hello` |
| 26 | if needEscape(s) { |
| 27 | t.Fatal("string does not need escaping") |
| 28 | } |
| 29 | if EscNonPrint(s) != s { |
| 30 | t.Fatal("string should not have changed") |
| 31 | } |
| 32 | s = `"hello"` |
| 33 | if EscNonPrint(s) != s { |
| 34 | t.Fatal("string should not have changed") |
| 35 | } |
| 36 | if EscNonPrint(`"hel\"lo"`) != `"hel\\"lo"` { |
| 37 | t.Fatal("did not get expected escaped string") |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | func hasNonPrintable(s string) bool { |
| 42 | for _, r := range s { |
| 43 | if !strconv.IsPrint(r) { |
| 44 | return true |
| 45 | } |
| 46 | } |
| 47 | return false |
| 48 | } |