Files
story/internal/volcsubtitle/protocol_test.go
T

54 lines
2.2 KiB
Go
Raw Normal View History

2026-09-06 17:04:11 +08:00
package volcsubtitle
import (
"encoding/base64"
"encoding/binary"
"testing"
)
func frame(body string) string {
b := append(make([]byte, 8), []byte(body)...)
copy(b, "subv")
binary.BigEndian.PutUint32(b[4:8], uint32(len(b)-8))
return base64.StdEncoding.EncodeToString(b)
}
func TestDecodeNativeSubtitle(t *testing.T) {
valid := `{"type":"subtitle","data":[{"userId":"device-a","roundId":0,"sequence":0,"definite":true,"paragraph":false,"text":"你好"},{"userId":"bot-a","roundId":0,"sequence":1,"definite":true,"paragraph":true,"text":"下午好"}]}`
p, err := Decode(frame(valid))
if err != nil || len(p.Data) != 2 || p.Data[0].Paragraph || p.Data[0].Text != "你好" {
t.Fatalf("%+v %v", p, err)
}
for _, s := range []string{"", "not base64!", base64.StdEncoding.EncodeToString([]byte("subv")), frame(`{"type":"other","data":[]}`), frame(`{"type":"subtitle","data":[{"userId":"a","sequence":0}]}`), frame(`{"type":"subtitle","data":[{"userId":"a","roundId":0,"sequence":-1}]}`)} {
if _, err := Decode(s); err == nil {
t.Errorf("accepted malformed packet %q", s)
}
}
decoded, _ := base64.StdEncoding.DecodeString(frame(valid))
decoded[7]++
if _, err := Decode(base64.StdEncoding.EncodeToString(decoded)); err == nil {
t.Fatal("accepted incorrect binary length")
}
}
func TestSignatureIsConversationScoped(t *testing.T) {
secret := []byte("dedicated-test-secret-32-bytes-long")
if Signature(secret, "a") == Signature(secret, "b") || Signature(secret, "a") == Signature([]byte("other"), "a") {
t.Fatal("signature must bind both secret and conversation")
}
}
func TestHardwareJSONSubtitle(t *testing.T) {
for _, body := range []string{
`{"type":"subtitle","deviceName":"test-device","productKey":"test-product","data":[{"userId":"input","roundId":1,"sequence":0,"text":"测试","definite":true}]}`,
`{"type":"subtitle","deviceName":"test-device","productKey":"test-product","data":[{"userId":"output","roundId":1,"sequence":1,"text":"","definite":true,"paragraph":true}]}`,
} {
for _, encoded := range []string{base64.StdEncoding.EncodeToString([]byte(body)), frame(body)} {
p, err := Decode(encoded)
if err != nil || p.DeviceName != "test-device" || p.ProductKey != "test-product" {
t.Fatalf("hardware packet=%+v err=%v", p, err)
}
}
}
}