Created
January 24, 2016 17:45
-
-
Save huljas/5f0b0d85519a1b0ba4a9 to your computer and use it in GitHub Desktop.
Go flatbuffers test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package flatbuffers | |
import ( | |
"github.com/ReforgedStudios/legion-gameserver/flatbuffers/messages" | |
flatbuffers "github.com/google/flatbuffers/go" | |
"github.com/stretchr/testify/assert" | |
"testing" | |
//"log" | |
) | |
func BuildMessage(b *flatbuffers.Builder, name string, id uint64) []byte { | |
// re-use the already-allocated Builder: | |
b.Reset() | |
// write the User object: | |
name_position := b.CreateByteString([]byte(name)) | |
messages.MessageStart(b) | |
messages.MessageAddId(b, id) | |
messages.MessageAddName(b, name_position) | |
message_position := messages.MessageEnd(b) | |
// finish the write operations by our User the root object: | |
b.Finish(message_position) | |
// return the byte slice containing encoded data: | |
return b.Bytes[b.Head():] | |
} | |
type InvalidDataError struct { | |
message string | |
} | |
func (e InvalidDataError) Error() string { | |
return e.message | |
} | |
func ReadUser(buf []byte) (name string, id uint64) { | |
// initialize a User reader from the given buffer: | |
message := messages.GetRootAsMessage(buf, 0) | |
// copy the user's id (since this is just a uint64): | |
id = message.Id() | |
// point the name variable to the bytes containing the encoded name: | |
name = string(message.Name()) | |
return | |
} | |
func TestOkFlatbuffers(t *testing.T) { | |
b := flatbuffers.NewBuilder(0) | |
buf := BuildMessage(b, "Arthur Dent", 42) | |
name, id := ReadUser(buf) | |
assert.Equal(t, "Arthur Dent", name) | |
assert.Equal(t, uint64(42), id) | |
} | |
func TestInvalidStringDataShouldPanic(t *testing.T) { | |
buf := []byte("hello world!") | |
var p interface{} | |
defer func() { | |
p = recover() | |
}() | |
_, _ = ReadUser(buf) | |
assert.NotNil(t, p) | |
} | |
func TestInvalidBinaryDataShouldPanic(t *testing.T) { | |
buf := []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} | |
var p interface{} | |
defer func() { | |
p = recover() | |
}() | |
_, _ = ReadUser(buf) | |
assert.NotNil(t, p) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace messages; | |
table Message { | |
id:ulong; | |
name:string; | |
} | |
root_type Message; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment