plugctl/plug_test.go

77 lines
2 KiB
Go
Raw Normal View History

2023-01-06 16:29:05 +11:00
package plugctl
import (
"bytes"
2023-01-06 17:52:03 +11:00
"crypto/rand"
2023-01-06 16:29:05 +11:00
"encoding/base64"
"io"
"testing"
)
func TestDecrypt(t *testing.T) {
// on message from hs100.sh
in64 := "AAAAKtDygfiL/5r31e+UtsWg1Iv5nPCR6LfEsNGlwOLYo4HyhueT9tTu36Lfog=="
in, err := base64.StdEncoding.DecodeString(in64)
if err != nil {
t.Fatalf("base64.DecodeString(%q) error: %v", in64, err)
}
2023-01-06 17:52:03 +11:00
t.Logf("in[:4] = %v", in[:4])
2023-01-06 16:29:05 +11:00
in = in[4:]
want := []byte(`{"system":{"set_relay_state":{"state":1}}}`)
2023-01-06 17:52:03 +11:00
got, err := io.ReadAll(newDecrypter(bytes.NewReader(in)))
2023-01-06 16:29:05 +11:00
if err != nil {
t.Fatalf("io.ReadAll(decryptReader) error: %v", err)
}
if !bytes.Equal(got, want) {
2023-01-06 17:52:03 +11:00
t.Errorf("io.ReadAll(decryptReader) = %q, want %q", got, want)
2023-01-06 16:29:05 +11:00
}
}
func TestEncrypt(t *testing.T) {
// on message from hs100.sh
want64 := "AAAAKtDygfiL/5r31e+UtsWg1Iv5nPCR6LfEsNGlwOLYo4HyhueT9tTu36Lfog=="
want, err := base64.StdEncoding.DecodeString(want64)
if err != nil {
t.Fatalf("base64.DecodeString(%q) error: %v", want64, err)
}
want = want[4:]
in := []byte(`{"system":{"set_relay_state":{"state":1}}}`)
var buf bytes.Buffer
2023-01-06 17:52:03 +11:00
if _, err := newEncrypter(&buf).Write(in); err != nil {
t.Fatalf("newEncrypter(buf).Write(in) error = %v", err)
}
2023-01-06 16:29:05 +11:00
if got := buf.Bytes(); !bytes.Equal(got, want) {
2023-01-06 17:52:03 +11:00
t.Errorf("buf.Bytes() = %02x, want %02x", got, want)
2023-01-06 16:29:05 +11:00
}
}
2023-01-06 17:52:03 +11:00
func TestEncryptDecrypt(t *testing.T) {
want := make([]byte, 64)
if _, err := rand.Read(want); err != nil {
t.Fatalf("rand.Read(want) error: %v", err)
}
var buf bytes.Buffer
newEncrypter(&buf).Write(want)
got, err := io.ReadAll(newDecrypter(&buf))
if err != nil {
t.Fatalf("io.ReadAll(newDecrypter(&buf))")
}
if !bytes.Equal(got, want) {
t.Errorf("decrypt(encrypt(%02x)) = %02x, want %02x", want, got, want)
}
}
func TestReadStatusFromRealPlug(t *testing.T) {
//t.Skip("Hits the real device")
p := Plug{Addr: "192.168.86.10:9999"}
resp, err := p.roundTrip(reqGetSysinfo)
if err != nil {
t.Errorf("Plug.roundTrip(%v) error = %v", reqGetSysinfo, err)
}
t.Logf("Plug.roundTrip(%v) = %#v", reqGetSysinfo, *resp.System.GetSysInfo)
}