2016-06-30 03:03:55 +03:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2017-01-13 12:06:51 +03:00
|
|
|
"fmt"
|
2016-06-30 03:03:55 +03:00
|
|
|
"io"
|
2017-01-13 12:06:51 +03:00
|
|
|
"io/ioutil"
|
2016-06-30 03:03:55 +03:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
type nopCloser struct{ io.Writer }
|
|
|
|
|
|
|
|
func (nopCloser) Close() error { return nil }
|
|
|
|
|
|
|
|
func TestTruncWriter(t *testing.T) {
|
|
|
|
const data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz987654321"
|
|
|
|
for n := 1; n <= 10; n++ {
|
|
|
|
var b bytes.Buffer
|
|
|
|
w := &truncWriter{w: nopCloser{&b}}
|
|
|
|
p := []byte(data)
|
|
|
|
for len(p) > 0 {
|
|
|
|
m := len(p)
|
|
|
|
if m > n {
|
|
|
|
m = n
|
|
|
|
}
|
|
|
|
w.Write(p[:m])
|
|
|
|
p = p[m:]
|
|
|
|
}
|
|
|
|
if b.String() != data[:len(data)-len(w.p)] {
|
|
|
|
t.Errorf("%d: %q", n, b.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-01-13 12:06:51 +03:00
|
|
|
|
|
|
|
func textMessages(num int) [][]byte {
|
|
|
|
messages := make([][]byte, num)
|
|
|
|
for i := 0; i < num; i++ {
|
|
|
|
msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i)
|
|
|
|
messages[i] = []byte(msg)
|
|
|
|
}
|
|
|
|
return messages
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkWriteNoCompression(b *testing.B) {
|
|
|
|
w := ioutil.Discard
|
2018-08-18 05:50:34 +03:00
|
|
|
c := newTestConn(nil, w, false)
|
2017-01-13 12:06:51 +03:00
|
|
|
messages := textMessages(100)
|
|
|
|
b.ResetTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
c.WriteMessage(TextMessage, messages[i%len(messages)])
|
|
|
|
}
|
|
|
|
b.ReportAllocs()
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkWriteWithCompression(b *testing.B) {
|
|
|
|
w := ioutil.Discard
|
2018-08-18 05:50:34 +03:00
|
|
|
c := newTestConn(nil, w, false)
|
2017-01-13 12:06:51 +03:00
|
|
|
messages := textMessages(100)
|
|
|
|
c.enableWriteCompression = true
|
|
|
|
c.newCompressionWriter = compressNoContextTakeover
|
|
|
|
b.ResetTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
c.WriteMessage(TextMessage, messages[i%len(messages)])
|
|
|
|
}
|
|
|
|
b.ReportAllocs()
|
|
|
|
}
|
2017-01-19 22:00:23 +03:00
|
|
|
|
|
|
|
func TestValidCompressionLevel(t *testing.T) {
|
2018-08-18 05:50:34 +03:00
|
|
|
c := newTestConn(nil, nil, false)
|
2017-01-19 22:00:23 +03:00
|
|
|
for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} {
|
|
|
|
if err := c.SetCompressionLevel(level); err == nil {
|
|
|
|
t.Errorf("no error for level %d", level)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, level := range []int{minCompressionLevel, maxCompressionLevel} {
|
|
|
|
if err := c.SetCompressionLevel(level); err != nil {
|
|
|
|
t.Errorf("error for level %d", level)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|