From a96c5496acc2c02814b17f872dc3914408f06b41 Mon Sep 17 00:00:00 2001 From: Patrick Peng Sun Date: Tue, 25 Apr 2017 16:48:24 +1000 Subject: [PATCH] read xml common header tested. --- encrypt_test.go | 9 ++++++--- inMsg.go | 15 +++++++++++++-- inMsg_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 inMsg_test.go diff --git a/encrypt_test.go b/encrypt_test.go index 5f74771..0a698c4 100644 --- a/encrypt_test.go +++ b/encrypt_test.go @@ -1,16 +1,19 @@ package main -import "testing" +import ( + "testing" +) -func setupConfig() { +func SetupConfig() { APIConfig = WechatAPIConfig{ "skdq8vklaurfqemfszuif", "cmtWK2teRnLOXyO5dw7lJkETv9jCeNAqYyguEu5D8gG", "wx876e233fde456b7b", "4a91aa328569b10a9fb97adeb8b0af58"} } + func TestEncodingMesage(t *testing.T) { - setupConfig() + SetupConfig() //明文: var msg = ` diff --git a/inMsg.go b/inMsg.go index b9bc7b1..1d7b1db 100644 --- a/inMsg.go +++ b/inMsg.go @@ -1,11 +1,15 @@ //analyze xml message package main +import ( + "encoding/xml" +) + //all xml message has these headers -type Header struct { +type CommonHeader struct { ToUserName string FromUserName string - CreatTime int64 + CreateTime int64 MsgType string } @@ -58,3 +62,10 @@ type LinkMsg struct { Url string MsgId int64 } + +//ReadCommonHeader parse xml of common field of wechat post message +func ReadCommonHeader(s string) CommonHeader { + var r = CommonHeader{} + xml.Unmarshal([]byte(s), &r) + return r +} diff --git a/inMsg_test.go b/inMsg_test.go new file mode 100644 index 0000000..1782463 --- /dev/null +++ b/inMsg_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "testing" +) + +func TestReadCommonHeader(t *testing.T) { + SetupConfig() + var msg = ` + +1492972518 + + + +` + + h := ReadCommonHeader(msg) + assertEqual(t, h.ToUserName, "gh_f09231355c68", "ToUserName failed") + assertEqual(t, h.FromUserName, "oUN420bxqFqlx0ZQHciUOesZO3PE", "FromUserName failed") + assertEqual(t, h.MsgType, "event", "MsgType failed") + //for weird reasons assertEqual does not work for integer + if h.CreateTime != 1492972518 { + errmsg := fmt.Sprintf("CreateTime should be 1492972518, not %d", h.CreateTime) + t.Error(errmsg) + } + +} + +func assertEqual(t *testing.T, a interface{}, b interface{}, message string) { + if a == b { + return + } + if len(message) == 0 { + message = fmt.Sprintf("%v != %v", a, b) + } + message = fmt.Sprintf("%v != %v", a, b) + t.Fatal(message) +}