pull/98/merge
Jiayu Yi 8 years ago committed by GitHub
commit e38cc87242
  1. 5
      bot.go
  2. 68
      local_test.go

@ -21,6 +21,8 @@ import (
// BotAPI allows you to interact with the Telegram Bot API. // BotAPI allows you to interact with the Telegram Bot API.
type BotAPI struct { type BotAPI struct {
APIEndpoint string `json:"api_endpoint"`
Token string `json:"token"` Token string `json:"token"`
Debug bool `json:"debug"` Debug bool `json:"debug"`
Buffer int `json:"buffer"` Buffer int `json:"buffer"`
@ -42,6 +44,7 @@ func NewBotAPI(token string) (*BotAPI, error) {
// It requires a token, provided by @BotFather on Telegram. // It requires a token, provided by @BotFather on Telegram.
func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) { func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
bot := &BotAPI{ bot := &BotAPI{
APIEndpoint: APIEndpoint,
Token: token, Token: token,
Client: client, Client: client,
Buffer: 100, Buffer: 100,
@ -59,7 +62,7 @@ func NewBotAPIWithClient(token string, client *http.Client) (*BotAPI, error) {
// MakeRequest makes a request to a specific endpoint with our token. // MakeRequest makes a request to a specific endpoint with our token.
func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) { func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error) {
method := fmt.Sprintf(APIEndpoint, bot.Token, endpoint) method := fmt.Sprintf(bot.APIEndpoint, bot.Token, endpoint)
resp, err := bot.Client.PostForm(method, params) resp, err := bot.Client.PostForm(method, params)
if err != nil { if err != nil {

@ -0,0 +1,68 @@
package tgbotapi
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
type APIRequest struct {
Body string
Path string
}
func MockTelegramAPI() (*httptest.Server, chan APIRequest, chan error) {
reqChan := make(chan APIRequest, 1)
errChan := make(chan error, 1)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
errChan <- err
return
}
apiReq := APIRequest{
Body: string(body),
Path: r.URL.Path,
}
reqChan <- apiReq
w.Write([]byte(`{"ok":true}`))
}))
return ts, reqChan, errChan
}
func TestSendWithMessageOffline(t *testing.T) {
ts, reqChan, errChan := MockTelegramAPI()
defer ts.Close()
bot := BotAPI{
APIEndpoint: ts.URL + "/bot%s/%s",
Client: http.DefaultClient,
}
msg := NewMessage(1, "Hello, World")
_, err := bot.Send(msg)
if err != nil {
t.Fatal(err)
}
var actual APIRequest
expected := APIRequest{
Body: "chat_id=1&disable_notification=false&disable_web_page_preview=false&text=Hello%2C+World",
Path: "/bot/sendMessage",
}
select {
case req := <-reqChan:
actual = req
case err := <-errChan:
t.Fatal(err)
}
if actual != expected {
t.Errorf("\nExpected:\n%+v\nActual:\n%+v\n", expected, actual)
}
}