colorable_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 TestColorable(t *testing.T) {
  60. if runtime.GOOS == "windows" {
  61. t.Skipf("skip this test on windows")
  62. }
  63. _, ok := NewColorableStdout().(*os.File)
  64. if !ok {
  65. t.Fatalf("should os.Stdout on UNIX")
  66. }
  67. _, ok = NewColorableStderr().(*os.File)
  68. if !ok {
  69. t.Fatalf("should os.Stdout on UNIX")
  70. }
  71. _, ok = NewColorable(os.Stdout).(*os.File)
  72. if !ok {
  73. t.Fatalf("should os.Stdout on UNIX")
  74. }
  75. }