colorable_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package colorable
  2. import (
  3. "bytes"
  4. "os"
  5. "runtime"
  6. "testing"
  7. )
  8. // checkEncoding checks that colorable is output encoding agnostic as long as
  9. // the encoding is a superset of ASCII. This implies that one byte not part of
  10. // an ANSI sequence must give exactly one byte in output
  11. func checkEncoding(t *testing.T, data []byte) {
  12. // Send non-UTF8 data to colorable
  13. b := bytes.NewBuffer(make([]byte, 0, 10))
  14. if b.Len() != 0 {
  15. t.FailNow()
  16. }
  17. // TODO move colorable wrapping outside the test
  18. c := NewNonColorable(b)
  19. c.Write(data)
  20. if b.Len() != len(data) {
  21. t.Fatalf("%d bytes expected, got %d", len(data), b.Len())
  22. }
  23. }
  24. func TestEncoding(t *testing.T) {
  25. checkEncoding(t, []byte{}) // Empty
  26. checkEncoding(t, []byte(`abc`)) // "abc"
  27. checkEncoding(t, []byte(`é`)) // "é" in UTF-8
  28. checkEncoding(t, []byte{233}) // 'é' in Latin-1
  29. }
  30. func TestNonColorable(t *testing.T) {
  31. var buf bytes.Buffer
  32. want := "hello"
  33. NewNonColorable(&buf).Write([]byte("\x1b[0m" + want + "\x1b[2J"))
  34. got := buf.String()
  35. if got != "hello" {
  36. t.Fatalf("want %q but %q", want, got)
  37. }
  38. buf.Reset()
  39. NewNonColorable(&buf).Write([]byte("\x1b["))
  40. got = buf.String()
  41. if got != "" {
  42. t.Fatalf("want %q but %q", "", got)
  43. }
  44. }
  45. func TestNonColorableNil(t *testing.T) {
  46. paniced := false
  47. func() {
  48. defer func() {
  49. recover()
  50. paniced = true
  51. }()
  52. NewNonColorable(nil)
  53. NewColorable(nil)
  54. }()
  55. if !paniced {
  56. t.Fatalf("should panic")
  57. }
  58. }
  59. func TestNonColorableESC(t *testing.T) {
  60. var b bytes.Buffer
  61. c := NewNonColorable(&b)
  62. c.Write([]byte{0x1b})
  63. if b.Len() > 0 {
  64. t.Fatalf("0 bytes expected, got %d", b.Len())
  65. }
  66. }
  67. func TestNonColorableBadESC(t *testing.T) {
  68. var b bytes.Buffer
  69. c := NewNonColorable(&b)
  70. c.Write([]byte{0x1b, 0x1b})
  71. if b.Len() > 0 {
  72. t.Fatalf("0 bytes expected, got %d", b.Len())
  73. }
  74. }
  75. func TestColorable(t *testing.T) {
  76. if runtime.GOOS == "windows" {
  77. t.Skipf("skip this test on windows")
  78. }
  79. _, ok := NewColorableStdout().(*os.File)
  80. if !ok {
  81. t.Fatalf("should os.Stdout on UNIX")
  82. }
  83. _, ok = NewColorableStderr().(*os.File)
  84. if !ok {
  85. t.Fatalf("should os.Stdout on UNIX")
  86. }
  87. _, ok = NewColorable(os.Stdout).(*os.File)
  88. if !ok {
  89. t.Fatalf("should os.Stdout on UNIX")
  90. }
  91. }