github.com/456vv/valexa@v1.0.2-0.20200706152242-1fb922d71ce5/Alexa_test.go (about)

     1  package valexa
     2  	
     3  import (
     4  	"testing"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"bufio"
     8  	"bytes"
     9  	"os"
    10  	"io"
    11  	"encoding/json"
    12  //	"fmt"
    13  )
    14  
    15  func init(){
    16  	os.Chdir("./test/data")
    17  }
    18  
    19  
    20  func Test_Alexa_1(testingT *testing.T){
    21  	echoApp := &EchoApplication{
    22  		ValidReqTimestamp	: testValidTime,
    23  		CertFolder			: "./AmazonCertFile",
    24  	}
    25  	alexa := &Alexa{
    26  		AppIdAttr	: "appid",
    27  	}
    28  	alexa.SetEchoApp("amzn1.ask.skill.594232d8-4095-499b-9ba3-11701107834d", echoApp)
    29  	
    30  	w := httptest.NewRecorder()
    31  	r, _ := http.ReadRequest(bufio.NewReader(bytes.NewReader(requestBody)))
    32  	alexa.ServeHTTP(w, r)
    33  }
    34  
    35  func EchoHTTPHandler(w http.ResponseWriter, r *http.Request) {
    36  	inf := r.Context().Value(r.URL.Path)
    37  	echoIntent, ok := inf.(*EchoIntent)
    38  	if !ok {
    39  		http.Error(w, "该路径没有绑定有效的处理程序", 500)
    40  	}
    41  	echoIntent.Response.OutputSpeech("Hello world from my new Echo test app!").SimpleCard("Hello World", "This is a test card.")
    42  	io.WriteString(w, echoIntent.Response.String())
    43  }
    44  
    45  func Test_Alexa_3(testingT *testing.T){
    46  	//这里也不测试了,原因是requestBody的参数过期了
    47  	//有空再更新了
    48  	return
    49  	echoApp := &EchoApplication{
    50  		ValidReqTimestamp	: testValidTime,
    51  		CertFolder			: "./AmazonCertFile",
    52  		HandleFunc     		: EchoHTTPHandler,
    53  	}
    54  	alexa := &Alexa{
    55  		AppIdAttr	: "appid",
    56  	}
    57  	alexa.SetEchoApp("amzn1.ask.skill.594232d8-4095-499b-9ba3-11701107834d", echoApp)
    58  	
    59  	w := httptest.NewRecorder()
    60  	r, _ := http.ReadRequest(bufio.NewReader(bytes.NewReader(requestBody)))
    61  	alexa.ServeHTTP(w, r)
    62  	
    63  	var echoResp *EchoResponse
    64  	err := json.NewDecoder(w.Body).Decode(&echoResp)
    65  	if err != nil {
    66  		testingT.Fatalf("错误:%v", err)
    67  	}
    68  	if echoResp.Response.Card.Title != "Hello World" {
    69  		testingT.Fatalf("错误的:%s", echoResp.Response.Card.Title)
    70  	}
    71  	if echoResp.Response.Card.Content != "This is a test card." {
    72  		testingT.Fatalf("错误的:%s", echoResp.Response.Card.Content)
    73  	}
    74  	if echoResp.Response.OutputSpeech.Text != "Hello world from my new Echo test app!" {
    75  		testingT.Fatalf("错误的:%s", echoResp.Response.Card.Content)
    76  	}
    77  }
    78