prepared_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package websocket
  5. import (
  6. "bytes"
  7. "compress/flate"
  8. "math/rand"
  9. "testing"
  10. )
  11. var preparedMessageTests = []struct {
  12. messageType int
  13. isServer bool
  14. enableWriteCompression bool
  15. compressionLevel int
  16. }{
  17. // Server
  18. {TextMessage, true, false, flate.BestSpeed},
  19. {TextMessage, true, true, flate.BestSpeed},
  20. {TextMessage, true, true, flate.BestCompression},
  21. {PingMessage, true, false, flate.BestSpeed},
  22. {PingMessage, true, true, flate.BestSpeed},
  23. // Client
  24. {TextMessage, false, false, flate.BestSpeed},
  25. {TextMessage, false, true, flate.BestSpeed},
  26. {TextMessage, false, true, flate.BestCompression},
  27. {PingMessage, false, false, flate.BestSpeed},
  28. {PingMessage, false, true, flate.BestSpeed},
  29. }
  30. func TestPreparedMessage(t *testing.T) {
  31. for _, tt := range preparedMessageTests {
  32. var data = []byte("this is a test")
  33. var buf bytes.Buffer
  34. c := newConn(fakeNetConn{Reader: nil, Writer: &buf}, tt.isServer, 1024, 1024)
  35. if tt.enableWriteCompression {
  36. c.newCompressionWriter = compressNoContextTakeover
  37. }
  38. c.SetCompressionLevel(tt.compressionLevel)
  39. // Seed random number generator for consistent frame mask.
  40. rand.Seed(1234)
  41. if err := c.WriteMessage(tt.messageType, data); err != nil {
  42. t.Fatal(err)
  43. }
  44. want := buf.String()
  45. pm, err := NewPreparedMessage(tt.messageType, data)
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. // Scribble on data to ensure that NewPreparedMessage takes a snapshot.
  50. copy(data, "hello world")
  51. // Seed random number generator for consistent frame mask.
  52. rand.Seed(1234)
  53. buf.Reset()
  54. if err := c.WritePreparedMessage(pm); err != nil {
  55. t.Fatal(err)
  56. }
  57. got := buf.String()
  58. if got != want {
  59. t.Errorf("write message != prepared message for %+v", tt)
  60. }
  61. }
  62. }