Преглед на файлове

Define `Event` and add tests for it.

Arto Bendiken преди 3 години
родител
ревизия
0a0289e0a7
променени са 3 файла, в които са добавени 54 реда и са изтрити 1 реда
  1. 23 0
      event.go
  2. 30 0
      event_test.go
  3. 1 1
      go.mod

+ 23 - 0
event.go

@@ -0,0 +1,23 @@
+package borealis
+
+import (
+	"encoding/json"
+)
+
+type Event struct {
+	Type uint16
+}
+
+func (event Event) MarshalJSON() ([]byte, error) {
+	array := []interface{}{event.Type}
+	return json.Marshal(array)
+}
+
+func (event *Event) UnmarshalJSON(input []byte) error {
+	array := []interface{}{}
+	if err := json.Unmarshal(input, &array); err != nil {
+		return err
+	}
+	event.Type = uint16(array[0].(float64))
+	return nil
+}

+ 30 - 0
event_test.go

@@ -0,0 +1,30 @@
+package borealis
+
+import (
+	"encoding/json"
+	"testing"
+)
+
+func TestEncodeEvent(t *testing.T) {
+	event := Event{Type: 0x1234}
+	output, err := json.Marshal(event)
+	if err != nil {
+		t.Error(err)
+	}
+	actual := string(output)
+	expected := "[4660]"
+	if actual != expected {
+		t.Errorf("expected %v, but got %v", expected, actual)
+	}
+}
+
+func TestDecodeEvent(t *testing.T) {
+	var actual Event
+	if err := json.Unmarshal([]byte("[4660]"), &actual); err != nil {
+		t.Error(err)
+	}
+	expected := Event{Type: 0x1234}
+	if actual != expected {
+		t.Errorf("expected %v, but got %v", expected, actual)
+	}
+}

+ 1 - 1
go.mod

@@ -6,12 +6,12 @@ replace github.com/aurora-is-near/aurora-events/go v0.0.0 => ./events/go
 
 require (
 	github.com/aurora-is-near/aurora-events/go v0.0.0
+	github.com/mr-tron/base58 v1.2.0
 	github.com/nats-io/nats.go v1.13.1-0.20211122170419-d7c1d78a50fc
 )
 
 require (
 	github.com/golang/protobuf v1.5.2 // indirect
-	github.com/mr-tron/base58 v1.2.0 // indirect
 	github.com/nats-io/nats-server/v2 v2.6.6 // indirect
 	github.com/nats-io/nkeys v0.3.0 // indirect
 	github.com/nats-io/nuid v1.0.1 // indirect