forked from ericdaugherty/alexa-skills-kit-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alexa_test.go
629 lines (530 loc) · 18.9 KB
/
alexa_test.go
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package alexa
import (
"encoding/json"
"errors"
"testing"
"time"
)
const applicationID = "amzn1.ask.skill.ABC123"
const recipeIntentString = `{
"session": {
"new": false,
"sessionId": "amzn1.echo-api.session.[unique-value-here]",
"attributes": {},
"user": {
"userId": "amzn1.ask.account.[unique-value-here]"
},
"application": {
"applicationId": "amzn1.ask.skill.ABC123"
}
},
"version": "1.0",
"request": {
"locale": "en-US",
"timestamp": "2016-10-27T21:06:28Z",
"type": "IntentRequest",
"requestId": "amzn1.echo-api.request.xyz789",
"intent": {
"slots": {
"Item": {
"name": "Item",
"value": "snowball"
}
},
"name": "RecipeIntent"
}
},
"context": {
"AudioPlayer": {
"playerActivity": "IDLE"
},
"System": {
"device": {
"supportedInterfaces": {
"AudioPlayer": {}
}
},
"application": {
"applicationId": "amzn1.ask.skill.[unique-value-here]"
},
"user": {
"userId": "amzn1.ask.account.[unique-value-here]"
}
}
}
}`
// TestAlexaJSON Verifies that the Alexa Struct parses an Alexa JSON String correctly.
func TestAlexaJSON(t *testing.T) {
request := createRecipieRequest()
if request.Version != "1.0" {
t.Error("Expected Request Version to be 1.0 but was", request.Version)
}
if request.Session.New {
t.Error("Expected Session.new to be false but was true.")
}
if request.Session.User.UserID != "amzn1.ask.account.[unique-value-here]" {
t.Error("Expected Session.User.UserId to be amzn1.ask.account.[unique-value-here] but was", request.Session.User.UserID)
}
if request.Request.RequestID != "amzn1.echo-api.request.xyz789" {
t.Error("Expected request.Request.RequestID to be amzn1.echo-api.request.xyz789 but was", request.Request.RequestID)
}
}
func TestAlexaAppIDValidation(t *testing.T) {
request := createRecipieRequest()
alexa := getAlexa()
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Expected ProcessRequest to succeed but got error", err)
}
alexa = &Alexa{ApplicationID: "amzn1.ask.skill.ABC123456", RequestHandler: &emptyRequestHandler{}}
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail due to invalid Application ID but no err was returned.")
}
alexa = &Alexa{ApplicationID: "", RequestHandler: &emptyRequestHandler{}}
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail due to an empty Application ID but no err was returned.")
}
alexa = &Alexa{ApplicationID: applicationID, RequestHandler: &emptyRequestHandler{}}
request.Session.Application.ApplicationID = ""
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail due to an empty Request Application ID but no err was returned.")
}
}
func TestAlexaTimestampValidation(t *testing.T) {
request := createRecipieRequest()
alexa := getAlexa()
duration, _ := time.ParseDuration("-145s")
request.Request.Timestamp = time.Now().Add(duration).Format(time.RFC3339)
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Expected ProcessRequest to succeed but got error", err)
}
duration, _ = time.ParseDuration("-151s")
request.Request.Timestamp = time.Now().Add(duration).Format(time.RFC3339)
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail to due to an invalid timetamp but no err was returned.")
}
duration, _ = time.ParseDuration("151s")
request.Request.Timestamp = time.Now().Add(duration).Format(time.RFC3339)
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail to due to an invalid timetamp but no err was returned.")
}
request.Request.Timestamp = "UNPARSEABLE"
_, err = alexa.ProcessRequest(request)
if err == nil {
t.Error("Expected ProcessRequest to fail because the timestamp could not be parsed but no err was returned")
}
alexa.SetTimestampTolerance(0)
duration, _ = time.ParseDuration("-1s")
request.Request.Timestamp = time.Now().Add(duration).Format(time.RFC3339)
_, err = alexa.ProcessRequest(request)
alexa.SetTimestampTolerance(150)
if err == nil {
t.Error("Expected ProcessRequest to fail to due to an invalid timetamp but no err was returned.")
}
// Test Disabled Timestamp
duration, _ = time.ParseDuration("151s")
request.Request.Timestamp = time.Now().Add(duration).Format(time.RFC3339)
alexa.IgnoreTimestamp = true
_, err = alexa.ProcessRequest(request)
if err != nil {
t.Error("Expected ProcessRequest to pass even with an invalid timestamp because validation is disabled.")
}
}
func TestAlexaOnSessionStartedCalled(t *testing.T) {
request := createRecipieRequest()
handler := &emptyRequestHandler{}
alexa := getAlexaWithHandler(handler)
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if handler.OnSessionStartedCalled {
t.Error("On SessionStarted was called when session was not new.")
}
handler = &emptyRequestHandler{}
alexa = getAlexaWithHandler(handler)
request.Session.New = true
_, err = alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if !handler.OnSessionStartedCalled {
t.Error("On SessionStarted was not called for a new session.")
}
handler = &emptyRequestHandler{}
alexa = getAlexaWithHandler(handler)
request.Session.New = true
handler.OnSessionStartThrowsErr = true
_, err = alexa.ProcessRequest(request)
if !handler.OnSessionStartedCalled {
t.Error("On SessionStarted was not called for a new session.")
}
if err == nil {
t.Error("OnSessionStart should have returned an error.")
}
}
func TestAlexaOnLaunchCalled(t *testing.T) {
request := createRecipieRequest()
request.Request.Type = launchRequestName
handler := &emptyRequestHandler{}
alexa := getAlexaWithHandler(handler)
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if !handler.OnLaunchCalled {
t.Error("On Launch was not called.")
}
handler = &emptyRequestHandler{}
alexa = getAlexaWithHandler(handler)
handler.OnLaunchThrowsErr = true
_, err = alexa.ProcessRequest(request)
if !handler.OnLaunchCalled {
t.Error("OnLaunch was not called.")
}
if err == nil {
t.Error("OnLaunch should have returned an error.")
}
}
func TestAlexaOnIntentCalled(t *testing.T) {
request := createRecipieRequest()
request.Request.Type = intentRequestName
handler := &emptyRequestHandler{}
alexa := getAlexaWithHandler(handler)
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if !handler.OnIntentCalled {
t.Error("OnIntent was not called.")
}
handler = &emptyRequestHandler{}
alexa = getAlexaWithHandler(handler)
handler.OnIntentThrowsErr = true
_, err = alexa.ProcessRequest(request)
if !handler.OnIntentCalled {
t.Error("OnIntent was not called.")
}
if err == nil {
t.Error("OnIntent should have returned an error.")
}
}
func TestAlexaOnSessionEndedCalled(t *testing.T) {
request := createRecipieRequest()
request.Request.Type = sessionEndedRequestName
handler := &emptyRequestHandler{}
alexa := getAlexaWithHandler(handler)
_, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if !handler.OnSessionEndedCalled {
t.Error("OnSessionEnded was not called.")
}
handler = &emptyRequestHandler{}
alexa = getAlexaWithHandler(handler)
handler.OnSessionEndedThrowsErr = true
_, err = alexa.ProcessRequest(request)
if !handler.OnSessionEndedCalled {
t.Error("OnSessionEnded was not called.")
}
if err == nil {
t.Error("OnSessionEnded should have returned an error.")
}
}
func TestAlexaSimpleTextResponse(t *testing.T) {
request := createRecipieRequest()
alexa := getAlexaWithHandler(&simpleResponseHandler{})
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if responseEnv.Response.OutputSpeech.Text != "Response Text" {
t.Errorf("Response Text should have been %s but was %s", "Response Text", responseEnv.Response.OutputSpeech.Text)
}
if responseEnv.Response.OutputSpeech.Type != "PlainText" {
t.Errorf("Response Type should have been %s but was %s", "PlainText", responseEnv.Response.OutputSpeech.Type)
}
if responseEnv.Response.Reprompt.OutputSpeech.Text != "Reprompt Text" {
t.Errorf("Response Text should have been %s but was %s", "Reprompt Text", responseEnv.Response.OutputSpeech.Text)
}
if responseEnv.Response.Reprompt.OutputSpeech.Type != "PlainText" {
t.Errorf("Response Type should have been %s but was %s", "PlainText", responseEnv.Response.OutputSpeech.Type)
}
}
func TestSimpleSSMLResponse(t *testing.T) {
request := createRecipieRequest()
alexa := getAlexaWithHandler(&simpleSSMLResponseHandler{})
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if responseEnv.Response.OutputSpeech.SSML != "<speak>This output speech uses SSML.</speak>" {
t.Errorf("Response Text should have been %s but was %s", "<speak>This output speech uses SSML.</speak>", responseEnv.Response.OutputSpeech.SSML)
}
if responseEnv.Response.OutputSpeech.Type != "SSML" {
t.Errorf("Response Type should have been %s but was %s", "SSML", responseEnv.Response.OutputSpeech.Type)
}
if responseEnv.Response.Reprompt.OutputSpeech.SSML != "<speak>This Reprompt speech uses SSML.</speak>" {
t.Errorf("Response Text should have been %s but was %s", "<speak>This Reprompt speech uses SSML.</speak>", responseEnv.Response.OutputSpeech.SSML)
}
if responseEnv.Response.Reprompt.OutputSpeech.Type != "SSML" {
t.Errorf("Response Type should have been %s but was %s", "SSML", responseEnv.Response.OutputSpeech.Type)
}
}
func TestCards(t *testing.T) {
request := createRecipieRequest()
cardHandler := &simpleCardResponseHandler{Type: "Simple"}
alexa := getAlexaWithHandler(cardHandler)
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if responseEnv.Response.Card.Type != "Simple" {
t.Errorf("Card Type should be Simple but was %s", responseEnv.Response.Card.Type)
}
if responseEnv.Response.Card.Content != "Simple Content" {
t.Errorf("Card Content should be 'Simple Content' but was %s", responseEnv.Response.Card.Content)
}
cardHandler.Type = "Standard"
responseEnv, err = alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if responseEnv.Response.Card.Type != "Standard" {
t.Errorf("Card Type should be Standard but was %s", responseEnv.Response.Card.Type)
}
if responseEnv.Response.Card.Text != "Standard Body Text" {
t.Errorf("Card Content should be 'Standard Body Text' but was %s", responseEnv.Response.Card.Text)
}
cardHandler.Type = "LinkAccount"
responseEnv, err = alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if responseEnv.Response.Card.Type != "LinkAccount" {
t.Errorf("Card Type should be LinkAccount but was %s", responseEnv.Response.Card.Type)
}
}
func TestAudioPlayer(t *testing.T) {
request := createRecipieRequest()
audioPlayerHandler := &simpleAudioPlayerResponseHandler{Type: "Simple"}
alexa := getAlexaWithHandler(audioPlayerHandler)
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if len(responseEnv.Response.Directives) != 1 {
t.Fatalf("Response should contain 1 directive but contains %d", len(responseEnv.Response.Directives))
}
exp := `{"type":"AudioPlayer.Play","playBehavior":"REPLACE_ALL","audioItem":{"stream":{"token":"track2-long-audio","url":"https://my-audio-hosting-site.com/audio/sample-song-2.mp3","offsetInMilliseconds":100}}}`
b, err := json.Marshal(responseEnv.Response.Directives[0])
if err != nil {
t.Fatalf("Error marshaling response. %s", err.Error())
}
if string(b) != exp {
t.Errorf("Expected JSON of "+exp+" but was %s", string(b))
}
}
func TestSimpleDialogDirective(t *testing.T) {
request := createRecipieRequest()
simpleDialogDirectiveResponseHandler := &simpleDialogDirectiveResponseHandler{Type: "Simple"}
alexa := getAlexaWithHandler(simpleDialogDirectiveResponseHandler)
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if len(responseEnv.Response.Directives) != 1 {
t.Fatalf("Response should contain 1 directive but contains %d", len(responseEnv.Response.Directives))
}
exp := `{"type":"Dialog.Delegate","updatedIntent":{"name":"PlanMyTrip","confirmationStatus":"NONE","slots":{"travelDate":{"name":"travelDate","confirmationStatus":"NONE","value":"2017-04-21"}}}}`
b, err := json.Marshal(responseEnv.Response.Directives[0])
if err != nil {
t.Fatalf("Error marshaling response. %s", err.Error())
}
if string(b) != exp {
t.Errorf("Expected JSON of "+exp+" but was %s", string(b))
}
}
func TestNoIntentDialogDirective(t *testing.T) {
request := createRecipieRequest()
simpleDialogDirectiveResponseHandler := &simpleDialogDirectiveResponseHandler{Type: "NoIntent"}
alexa := getAlexaWithHandler(simpleDialogDirectiveResponseHandler)
responseEnv, err := alexa.ProcessRequest(request)
if err != nil {
t.Error("Error processing request. " + err.Error())
}
if len(responseEnv.Response.Directives) != 1 {
t.Fatalf("Response should contain 1 directive but contains %d", len(responseEnv.Response.Directives))
}
exp := `{"type":"Dialog.Delegate"}`
b, err := json.Marshal(responseEnv.Response.Directives[0])
if err != nil {
t.Fatalf("Error marshaling response. %s", err.Error())
}
if string(b) != exp {
t.Errorf("Expected JSON of "+exp+" but was %s", string(b))
}
}
func getAlexa() *Alexa {
return &Alexa{ApplicationID: applicationID, RequestHandler: &emptyRequestHandler{}}
}
func getAlexaWithHandler(handler RequestHandler) *Alexa {
return &Alexa{ApplicationID: applicationID, RequestHandler: handler}
}
func createRecipieRequest() *RequestEnvelope {
var request RequestEnvelope
var jsonBlob = []byte(recipeIntentString)
json.Unmarshal(jsonBlob, &request)
request.Request.Timestamp = time.Now().Format(time.RFC3339)
return &request
}
type emptyRequestHandler struct {
OnSessionStartedCalled bool
OnSessionStartThrowsErr bool
OnLaunchCalled bool
OnLaunchThrowsErr bool
OnIntentCalled bool
OnIntentThrowsErr bool
OnSessionEndedCalled bool
OnSessionEndedThrowsErr bool
}
func (h *emptyRequestHandler) OnSessionStarted(*Request, *Session, *Response) error {
h.OnSessionStartedCalled = true
if h.OnSessionStartThrowsErr {
return errors.New("Error in OnSessionStarted")
}
return nil
}
func (h *emptyRequestHandler) OnLaunch(*Request, *Session, *Response) error {
h.OnLaunchCalled = true
if h.OnLaunchThrowsErr {
return errors.New("Error in OnLaunch")
}
return nil
}
func (h *emptyRequestHandler) OnIntent(*Request, *Session, *Response) error {
h.OnIntentCalled = true
if h.OnIntentThrowsErr {
return errors.New("Error in OnIntent")
}
return nil
}
func (h *emptyRequestHandler) OnSessionEnded(*Request, *Session, *Response) error {
h.OnSessionEndedCalled = true
if h.OnSessionEndedThrowsErr {
return errors.New("Error in OnSessionEnded")
}
return nil
}
type simpleResponseHandler struct {
}
func (h *simpleResponseHandler) OnSessionStarted(*Request, *Session, *Response) error {
return nil
}
func (h *simpleResponseHandler) OnLaunch(*Request, *Session, *Response) error {
return nil
}
func (h *simpleResponseHandler) OnIntent(request *Request, session *Session, response *Response) error {
response.SetOutputText("Response Text")
response.SetRepromptText("Reprompt Text")
return nil
}
func (h *simpleResponseHandler) OnSessionEnded(*Request, *Session, *Response) error {
return nil
}
type simpleSSMLResponseHandler struct {
}
func (h *simpleSSMLResponseHandler) OnSessionStarted(*Request, *Session, *Response) error {
return nil
}
func (h *simpleSSMLResponseHandler) OnLaunch(*Request, *Session, *Response) error {
return nil
}
func (h *simpleSSMLResponseHandler) OnIntent(request *Request, session *Session, response *Response) error {
response.SetOutputSSML("<speak>This output speech uses SSML.</speak>")
response.SetRepromptSSML("<speak>This Reprompt speech uses SSML.</speak>")
return nil
}
func (h *simpleSSMLResponseHandler) OnSessionEnded(*Request, *Session, *Response) error {
return nil
}
type simpleCardResponseHandler struct {
Type string
}
func (h *simpleCardResponseHandler) OnSessionStarted(*Request, *Session, *Response) error {
return nil
}
func (h *simpleCardResponseHandler) OnLaunch(*Request, *Session, *Response) error {
return nil
}
func (h *simpleCardResponseHandler) OnIntent(request *Request, session *Session, response *Response) error {
switch h.Type {
case "Simple":
response.SetSimpleCard("Simple Title", "Simple Content")
case "Standard":
response.SetStandardCard("Standard Title", "Standard Body Text", "http://small.url", "http://large.url")
case "LinkAccount":
response.SetLinkAccountCard()
}
response.SetOutputSSML("<speak>This output speech uses SSML.</speak>")
response.SetRepromptSSML("<speak>This Reprompt speech uses SSML.</speak>")
return nil
}
func (h *simpleCardResponseHandler) OnSessionEnded(*Request, *Session, *Response) error {
return nil
}
type simpleAudioPlayerResponseHandler struct {
Type string
}
func (h *simpleAudioPlayerResponseHandler) OnSessionStarted(*Request, *Session, *Response) error {
return nil
}
func (h *simpleAudioPlayerResponseHandler) OnLaunch(*Request, *Session, *Response) error {
return nil
}
func (h *simpleAudioPlayerResponseHandler) OnIntent(request *Request, session *Session, response *Response) error {
response.AddAudioPlayer("AudioPlayer.Play", "REPLACE_ALL", "track2-long-audio", "https://my-audio-hosting-site.com/audio/sample-song-2.mp3", 100)
return nil
}
func (h *simpleAudioPlayerResponseHandler) OnSessionEnded(*Request, *Session, *Response) error {
return nil
}
type simpleDialogDirectiveResponseHandler struct {
Type string
}
func (h *simpleDialogDirectiveResponseHandler) OnSessionStarted(*Request, *Session, *Response) error {
return nil
}
func (h *simpleDialogDirectiveResponseHandler) OnLaunch(*Request, *Session, *Response) error {
return nil
}
func (h *simpleDialogDirectiveResponseHandler) OnIntent(request *Request, session *Session, response *Response) error {
switch h.Type {
case "Simple":
i := &Intent{
Name: "PlanMyTrip",
ConfirmationStatus: "NONE",
Slots: map[string]IntentSlot{
"travelDate": IntentSlot{
Name: "travelDate",
ConfirmationStatus: "NONE",
Value: "2017-04-21",
},
},
}
response.AddDialogDirective("Dialog.Delegate", "", "", i)
case "NoIntent":
response.AddDialogDirective("Dialog.Delegate", "", "", nil)
}
return nil
}
func (h *simpleDialogDirectiveResponseHandler) OnSessionEnded(*Request, *Session, *Response) error {
return nil
}