Skip to content

Instantly share code, notes, and snippets.

@superloach
Last active January 1, 2021 05:12
Show Gist options
  • Save superloach/a04c8b1e8678ed61be62f519bbb3d679 to your computer and use it in GitHub Desktop.
Save superloach/a04c8b1e8678ed61be62f519bbb3d679 to your computer and use it in GitHub Desktop.
dismock gateway testing

this is a very basic example that swaps the ws connection in dismock for one that allows mocking events. it then tests this by sending a status update and comparing results.

everything (hello, ready, event parsing) is done manually right now, but the general idea is that we can mock all the gateway events, both incoming and outgoing.

package main_test
import (
"context"
"encoding/json"
"reflect"
"testing"
"github.com/diamondburned/arikawa/v2/discord"
"github.com/diamondburned/arikawa/v2/gateway"
"github.com/diamondburned/arikawa/v2/utils/wsutil"
"github.com/mavolin/dismock/v2/pkg/dismock"
)
type Connection struct {
Recv chan wsutil.Event
Sent chan []byte
}
func (c Connection) Dial(_ context.Context, addr string) error {
return nil
}
func (c Connection) Listen() <-chan wsutil.Event {
return c.Recv
}
func (c Connection) Send(_ context.Context, data []byte) error {
c.Sent <- data
return nil
}
func (c Connection) Close() error {
return nil
}
func Event(code wsutil.OPCode, name string, evt gateway.Event) []byte {
data1, _ := json.Marshal(evt)
data2, _ := json.Marshal(wsutil.OP{
Code: code,
Data: data1,
EventName: name,
})
return data2
}
func TestGatemock(t *testing.T) {
m, s := dismock.NewSession(t)
conn := Connection{
Recv: make(chan wsutil.Event),
Sent: make(chan []byte),
}
s.Gateway.WS = wsutil.NewCustom(conn, "")
done := make(chan gateway.UpdateStatusData, 1)
go func() {
conn.Recv <- wsutil.Event{
Data: Event(10, "", gateway.HelloEvent{
HeartbeatInterval: 45000,
}),
}
_ = <-conn.Sent // identify
conn.Recv <- wsutil.Event{
Data: Event(0, "READY", gateway.ReadyEvent{}), // empty for now, should actually test
}
data := <-conn.Sent
op, err := wsutil.DecodeOP(wsutil.Event{
Data: data,
})
if err != nil {
t.Errorf("decode op %s: %w", data, err)
}
if op.Code != gateway.StatusUpdateOP {
t.Errorf("expect %d\ngot %d", gateway.StatusUpdateOP, op.Code)
}
us := gateway.UpdateStatusData{}
err = json.Unmarshal(op.Data, &us)
if err != nil {
t.Errorf("unmarshal update status %s: %w", op.Data, err)
}
done <- us
}()
s.AddHandler(func(*gateway.MessageCreateEvent) {})
err := s.Gateway.Open()
if err != nil {
t.Errorf("gateway open: %s", err)
}
expect := gateway.UpdateStatusData{
Activities: &[]discord.Activity{{
Name: "foo",
Type: discord.GameActivity,
}},
}
err = s.Gateway.UpdateStatus(expect)
if err != nil {
t.Errorf("update status: %s", err)
}
got := <-done
if !reflect.DeepEqual(expect, got) {
t.Errorf("expect %#v\ngot %#v", expect, got)
}
m.Eval()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment