compression_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package websocket
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "testing"
  8. )
  9. type nopCloser struct{ io.Writer }
  10. func (nopCloser) Close() error { return nil }
  11. func TestTruncWriter(t *testing.T) {
  12. const data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz987654321"
  13. for n := 1; n <= 10; n++ {
  14. var b bytes.Buffer
  15. w := &truncWriter{w: nopCloser{&b}}
  16. p := []byte(data)
  17. for len(p) > 0 {
  18. m := len(p)
  19. if m > n {
  20. m = n
  21. }
  22. w.Write(p[:m])
  23. p = p[m:]
  24. }
  25. if b.String() != data[:len(data)-len(w.p)] {
  26. t.Errorf("%d: %q", n, b.String())
  27. }
  28. }
  29. }
  30. func textMessages(num int) [][]byte {
  31. messages := make([][]byte, num)
  32. for i := 0; i < num; i++ {
  33. msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i)
  34. messages[i] = []byte(msg)
  35. }
  36. return messages
  37. }
  38. func BenchmarkWriteNoCompression(b *testing.B) {
  39. w := ioutil.Discard
  40. c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024)
  41. messages := textMessages(100)
  42. b.ResetTimer()
  43. for i := 0; i < b.N; i++ {
  44. c.WriteMessage(TextMessage, messages[i%len(messages)])
  45. }
  46. b.ReportAllocs()
  47. }
  48. func BenchmarkWriteWithCompression(b *testing.B) {
  49. w := ioutil.Discard
  50. c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024)
  51. messages := textMessages(100)
  52. c.enableWriteCompression = true
  53. c.newCompressionWriter = compressNoContextTakeover
  54. b.ResetTimer()
  55. for i := 0; i < b.N; i++ {
  56. c.WriteMessage(TextMessage, messages[i%len(messages)])
  57. }
  58. b.ReportAllocs()
  59. }
  60. func TestValidCompressionLevel(t *testing.T) {
  61. c := newConn(fakeNetConn{}, false, 1024, 1024)
  62. for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} {
  63. if err := c.SetCompressionLevel(level); err == nil {
  64. t.Errorf("no error for level %d", level)
  65. }
  66. }
  67. for _, level := range []int{minCompressionLevel, maxCompressionLevel} {
  68. if err := c.SetCompressionLevel(level); err != nil {
  69. t.Errorf("error for level %d", level)
  70. }
  71. }
  72. }