1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
package slack
import (
"encoding/json"
"net/http"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPostWebhook_OK(t *testing.T) {
once.Do(startServer)
var receivedPayload WebhookMessage
http.HandleFunc("/webhook", func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&receivedPayload)
if err != nil {
t.Errorf("Request contained invalid JSON, %s", err)
}
response := []byte(`{}`)
rw.Write(response)
})
url := "http://" + serverAddr + "/webhook"
payload := &WebhookMessage{
Text: "Test Text",
Attachments: []Attachment{
{
Text: "Foo",
},
},
}
err := PostWebhook(url, payload)
if err != nil {
t.Errorf("Expected not to receive error: %s", err)
}
if !reflect.DeepEqual(payload, &receivedPayload) {
t.Errorf("Payload did not match\nwant: %#v\n got: %#v", payload, receivedPayload)
}
}
func TestPostWebhook_NotOK(t *testing.T) {
once.Do(startServer)
http.HandleFunc("/webhook2", func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusInternalServerError)
rw.Write([]byte("500 - Something bad happened!"))
})
url := "http://" + serverAddr + "/webhook2"
err := PostWebhook(url, &WebhookMessage{})
if err == nil {
t.Errorf("Expected to receive error")
}
}
func TestWebhookMessage_WithBlocks(t *testing.T) {
textBlockObject := NewTextBlockObject("plain_text", "text", false, false)
sectionBlock := NewSectionBlock(textBlockObject, nil, nil)
singleBlock := &Blocks{BlockSet: []Block{sectionBlock}}
twoBlocks := &Blocks{BlockSet: []Block{sectionBlock, sectionBlock}}
msgSingleBlock := WebhookMessage{Blocks: singleBlock}
assert.Equal(t, 1, len(msgSingleBlock.Blocks.BlockSet))
msgJsonSingleBlock, _ := json.Marshal(msgSingleBlock)
assert.Equal(t, `{"blocks":[{"type":"section","text":{"type":"plain_text","text":"text"}}]}`, string(msgJsonSingleBlock))
msgTwoBlocks := WebhookMessage{Blocks: twoBlocks}
assert.Equal(t, 2, len(msgTwoBlocks.Blocks.BlockSet))
msgJsonTwoBlocks, _ := json.Marshal(msgTwoBlocks)
assert.Equal(t, `{"blocks":[{"type":"section","text":{"type":"plain_text","text":"text"}},{"type":"section","text":{"type":"plain_text","text":"text"}}]}`, string(msgJsonTwoBlocks))
msgNoBlocks := WebhookMessage{Text: "foo"}
msgJsonNoBlocks, _ := json.Marshal(msgNoBlocks)
assert.Equal(t, `{"text":"foo"}`, string(msgJsonNoBlocks))
}
|