colorable_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. NewNonColorable(b).Write(data)
  19. if b.Len() != len(data) {
  20. t.Fatalf("%d bytes expected, got %d", len(data), b.Len())
  21. }
  22. }
  23. func TestEncoding(t *testing.T) {
  24. checkEncoding(t, []byte{}) // Empty
  25. checkEncoding(t, []byte(`abc`)) // "abc"
  26. checkEncoding(t, []byte(`é`)) // "é" in UTF-8
  27. checkEncoding(t, []byte{233}) // 'é' in Latin-1
  28. }
  29. func TestNonColorable(t *testing.T) {
  30. var buf bytes.Buffer
  31. want := "hello"
  32. NewNonColorable(&buf).Write([]byte("\x1b[0m" + want + "\x1b[2J"))
  33. got := buf.String()
  34. if got != "hello" {
  35. t.Fatalf("want %q but %q", want, got)
  36. }
  37. buf.Reset()
  38. NewNonColorable(&buf).Write([]byte("\x1b["))
  39. got = buf.String()
  40. if got != "" {
  41. t.Fatalf("want %q but %q", "", got)
  42. }
  43. }
  44. func TestNonColorableNil(t *testing.T) {
  45. paniced := false
  46. func() {
  47. defer func() {
  48. recover()
  49. paniced = true
  50. }()
  51. NewNonColorable(nil)
  52. NewColorable(nil)
  53. }()
  54. if !paniced {
  55. t.Fatalf("should panic")
  56. }
  57. }
  58. func TestNonColorableESC(t *testing.T) {
  59. var b bytes.Buffer
  60. NewNonColorable(&b).Write([]byte{0x1b})
  61. if b.Len() > 0 {
  62. t.Fatalf("0 bytes expected, got %d", b.Len())
  63. }
  64. }
  65. func TestNonColorableBadESC(t *testing.T) {
  66. var b bytes.Buffer
  67. NewNonColorable(&b).Write([]byte{0x1b, 0x1b})
  68. if b.Len() > 0 {
  69. t.Fatalf("0 bytes expected, got %d", b.Len())
  70. }
  71. }
  72. func TestColorable(t *testing.T) {
  73. if runtime.GOOS == "windows" {
  74. t.Skipf("skip this test on windows")
  75. }
  76. _, ok := NewColorableStdout().(*os.File)
  77. if !ok {
  78. t.Fatalf("should os.Stdout on UNIX")
  79. }
  80. _, ok = NewColorableStderr().(*os.File)
  81. if !ok {
  82. t.Fatalf("should os.Stdout on UNIX")
  83. }
  84. _, ok = NewColorable(os.Stdout).(*os.File)
  85. if !ok {
  86. t.Fatalf("should os.Stdout on UNIX")
  87. }
  88. }