fix the chat.Message with empty Text and Extra message doesn't contain an empty "text" field after marshaled into json. close #151

This commit is contained in:
Tnze
2022-03-09 10:46:59 +08:00
parent cf25807f68
commit ec4eef2331
2 changed files with 58 additions and 1 deletions

View File

@ -2,7 +2,9 @@ package chat_test
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tnze/go-mc/chat"
@ -134,6 +136,31 @@ func TestMessage_Append_issue148(t *testing.T) {
}
}
func TestMessage_MarshalJSON_issue151(t *testing.T) {
// The "text" field should be omitted when "translate" exist.
// And NOT omitted when "extra" so.
// That is, we should correctly generate these chat messages:
// {"text":"","extra":["str1", "str2"]} and
// {"translate":"translation.test.escape","with":["str1","str2"]}
mustJson := func(msg *chat.Message) string {
data, err := json.Marshal(msg)
if err != nil {
t.Fatal(err)
}
return string(data)
}
// "" + "Hello, world!"
msg1 := chat.Text("").Append(chat.TranslateMsg("translation.test.none"))
if msg := mustJson(&msg1); !strings.Contains(msg, "text") {
t.Fatalf("%s doesn't contain %s", msg, "text")
}
//
msg2 := chat.TranslateMsg("translation.test.none")
if msg := mustJson(&msg2); strings.Contains(msg, "text") {
t.Fatalf("%s contains %s", msg, "text")
}
}
func ExampleTranslateMsg() {
fmt.Println(chat.TranslateMsg("translation.test.none"))
fmt.Println(chat.TranslateMsg(