2017-03-09 02:03:47 +08:00
|
|
|
// Copyright 2016 fatedier, fatedier@gmail.com
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package msg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/binary"
|
2017-03-10 02:01:17 +08:00
|
|
|
"reflect"
|
2017-03-09 02:03:47 +08:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
2018-05-08 02:13:30 +08:00
|
|
|
"github.com/fatedier/frp/models/errors"
|
2017-03-09 02:03:47 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type TestStruct struct{}
|
|
|
|
|
|
|
|
func TestPack(t *testing.T) {
|
|
|
|
assert := assert.New(t)
|
|
|
|
|
|
|
|
var (
|
|
|
|
msg Message
|
|
|
|
buffer []byte
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
// error type
|
|
|
|
msg = &TestStruct{}
|
|
|
|
buffer, err = Pack(msg)
|
|
|
|
assert.Error(err, errors.ErrMsgType.Error())
|
|
|
|
|
|
|
|
// correct
|
|
|
|
msg = &Ping{}
|
|
|
|
buffer, err = Pack(msg)
|
|
|
|
assert.NoError(err)
|
|
|
|
b := bytes.NewBuffer(nil)
|
|
|
|
b.WriteByte(TypePing)
|
|
|
|
binary.Write(b, binary.BigEndian, int64(2))
|
|
|
|
b.WriteString("{}")
|
|
|
|
assert.True(bytes.Equal(b.Bytes(), buffer))
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestUnPack(t *testing.T) {
|
|
|
|
assert := assert.New(t)
|
|
|
|
|
|
|
|
var (
|
|
|
|
msg Message
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
|
|
|
// error message type
|
|
|
|
msg, err = UnPack('-', []byte("{}"))
|
|
|
|
assert.Error(err)
|
|
|
|
|
|
|
|
// correct
|
|
|
|
msg, err = UnPack(TypePong, []byte("{}"))
|
|
|
|
assert.NoError(err)
|
2017-03-10 02:01:17 +08:00
|
|
|
assert.Equal(reflect.TypeOf(msg).Elem(), reflect.TypeOf(Pong{}))
|
2017-03-09 02:03:47 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestUnPackInto(t *testing.T) {
|
|
|
|
assert := assert.New(t)
|
|
|
|
|
|
|
|
var err error
|
|
|
|
|
|
|
|
// correct type
|
|
|
|
pongMsg := &Pong{}
|
|
|
|
err = UnPackInto([]byte("{}"), pongMsg)
|
|
|
|
assert.NoError(err)
|
|
|
|
|
|
|
|
// wrong type
|
|
|
|
loginMsg := &Login{}
|
|
|
|
err = UnPackInto([]byte(`{"version": 123}`), loginMsg)
|
|
|
|
assert.Error(err)
|
|
|
|
}
|