-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_lambda.py
More file actions
1486 lines (1196 loc) · 70.6 KB
/
Copy pathtest_lambda.py
File metadata and controls
1486 lines (1196 loc) · 70.6 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Comprehensive test suite for Alexa-LLM Lambda function.
Covers:
- lambda_function: all intent handlers, routing, response builder
- groq_provider: API success, errors, prompt construction
- gemini_provider: API success, errors, role mapping, prompt construction
- openrouter_provider: API success, errors, prompt construction
- dynamo: all CRUD paths, missing items, env-var table name
"""
import io
import json
import os
import sys
import unittest
from unittest.mock import MagicMock, patch, call
# ── Environment must be set before any project import ──────────────────────────
os.environ.setdefault("LLM_PROVIDER", "groq")
os.environ.setdefault("GROQ_API_KEY", "test-groq-key")
os.environ.setdefault("GEMINI_API_KEY", "test-gemini-key")
os.environ.setdefault("OPENROUTER_API_KEY", "test-openrouter-key")
os.environ.setdefault("DYNAMODB_TABLE", "TestTable")
import lambda_function
# ══════════════════════════════════════════════════════════════════════════════
# Helpers
# ══════════════════════════════════════════════════════════════════════════════
def make_event(
request_type,
intent_name=None,
query=None,
question=None,
context_value=None,
session_new=True,
user_id="test-user-id",
session_reason=None,
session_attributes=None,
):
"""Build a minimal but valid Alexa request event."""
event = {
"version": "1.0",
"session": {
"new": session_new,
"sessionId": "amzn1.echo-api.session.test",
"application": {"applicationId": "amzn1.ask.skill.test"},
"attributes": session_attributes or {},
"user": {"userId": user_id},
},
"context": {
"System": {
"application": {"applicationId": "amzn1.ask.skill.test"},
"user": {"userId": user_id},
"device": {
"deviceId": "amzn1.ask.device.test",
"supportedInterfaces": {},
},
"apiEndpoint": "https://api.amazonalexa.com",
"apiAccessToken": "test-token",
}
},
"request": {"type": request_type, "requestId": "amzn1.echo-api.request.test"},
}
if request_type == "IntentRequest":
slots = {}
if query is not None:
slots["query"] = {"name": "query", "value": query, "confirmationStatus": "NONE"}
if question is not None:
slots["question"] = {"name": "question", "value": question, "confirmationStatus": "NONE"}
if context_value is not None:
slots["context"] = {"name": "context", "value": context_value, "confirmationStatus": "NONE"}
event["request"]["intent"] = {
"name": intent_name,
"confirmationStatus": "NONE",
"slots": slots,
}
if request_type == "SessionEndedRequest":
event["request"]["reason"] = session_reason or "USER_INITIATED"
return event
def get_speech(response):
return response["response"]["outputSpeech"]["text"]
def get_reprompt(response):
return response["response"].get("reprompt", {}).get("outputSpeech", {}).get("text")
def make_urlopen_mock(body: dict, status: int = 200):
"""Return a context-manager mock that yields a fake HTTP response."""
encoded = json.dumps(body).encode("utf-8")
mock_response = MagicMock()
mock_response.read.return_value = encoded
mock_response.status = status
mock_response.__enter__ = lambda s: s
mock_response.__exit__ = MagicMock(return_value=False)
return mock_response
# ══════════════════════════════════════════════════════════════════════════════
# 1. build_response
# ══════════════════════════════════════════════════════════════════════════════
class TestBuildResponse(unittest.TestCase):
def test_basic_structure(self):
r = lambda_function.build_response("Hello")
self.assertEqual(r["version"], "1.0")
self.assertIn("response", r)
self.assertIn("sessionAttributes", r)
def test_speech_text(self):
r = lambda_function.build_response("Hello there")
self.assertEqual(get_speech(r), "Hello there")
def test_plain_text_type(self):
r = lambda_function.build_response("Hi")
self.assertEqual(r["response"]["outputSpeech"]["type"], "PlainText")
def test_session_stays_open_by_default(self):
r = lambda_function.build_response("Hi")
self.assertFalse(r["response"]["shouldEndSession"])
def test_session_ends_when_requested(self):
r = lambda_function.build_response("Bye", should_end=True)
self.assertTrue(r["response"]["shouldEndSession"])
def test_reprompt_present_when_session_open(self):
r = lambda_function.build_response("Hi")
self.assertIsNotNone(get_reprompt(r))
self.assertTrue(len(get_reprompt(r)) > 0)
def test_no_reprompt_when_session_ends(self):
r = lambda_function.build_response("Bye", should_end=True)
self.assertIsNone(get_reprompt(r))
def test_custom_session_attributes(self):
attrs = {"foo": "bar", "count": 3}
r = lambda_function.build_response("Hi", session_attributes=attrs)
self.assertEqual(r["sessionAttributes"], attrs)
def test_default_session_attributes_are_empty_dict(self):
r = lambda_function.build_response("Hi")
self.assertEqual(r["sessionAttributes"], {})
def test_empty_speech_string(self):
r = lambda_function.build_response("")
self.assertEqual(get_speech(r), "")
# ══════════════════════════════════════════════════════════════════════════════
# 2. LaunchRequest
# ══════════════════════════════════════════════════════════════════════════════
class TestLaunchRequest(unittest.TestCase):
def test_returns_greeting(self):
event = make_event("LaunchRequest")
r = lambda_function.lambda_handler(event, None)
self.assertEqual(r["version"], "1.0")
self.assertFalse(r["response"]["shouldEndSession"])
def test_greeting_is_non_empty(self):
event = make_event("LaunchRequest")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(len(get_speech(r)) > 0)
def test_session_stays_open(self):
event = make_event("LaunchRequest")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 3. AskClaudeIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestAskIntent(unittest.TestCase):
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="Stoicism is a philosophy of resilience.")
def test_success_with_query_slot(self, mock_llm, mock_get, mock_save, mock_facts, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="what is stoicism")
r = lambda_function.lambda_handler(event, None)
self.assertEqual(get_speech(r), "Stoicism is a philosophy of resilience.")
mock_llm.assert_called_once_with("what is stoicism", [], "")
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="Stoicism is about self-control.")
def test_success_with_question_slot(self, mock_llm, mock_get, mock_save, mock_facts, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", question="tell me about stoicism")
r = lambda_function.lambda_handler(event, None)
self.assertEqual(get_speech(r), "Stoicism is about self-control.")
mock_llm.assert_called_once_with("tell me about stoicism", [], "")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
def test_no_query_returns_prompt(self, mock_get, mock_save, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("didn't catch", get_speech(r))
mock_save.assert_not_called()
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", side_effect=Exception("API timeout"))
def test_llm_failure_returns_error_message(self, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="hello")
r = lambda_function.lambda_handler(event, None)
self.assertIn("trouble", get_speech(r))
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", side_effect=Exception("API timeout"))
def test_llm_failure_does_not_save_history(self, mock_llm, mock_get, mock_save, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="hello")
lambda_function.lambda_handler(event, None)
mock_save.assert_not_called()
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[
{"role": "user", "content": "what is stoicism"},
{"role": "assistant", "content": "Stoicism is a philosophy."},
])
@patch("lambda_function.call_llm", return_value="Epictetus was a Stoic philosopher.")
def test_history_passed_to_llm(self, mock_llm, mock_get, mock_save, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="who is epictetus")
lambda_function.lambda_handler(event, None)
_, history_arg, _ = mock_llm.call_args[0]
self.assertEqual(len(history_arg), 2)
self.assertEqual(history_arg[0]["role"], "user")
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="Sure.")
def test_history_updated_with_new_turn(self, mock_llm, mock_get, mock_save, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="test question")
lambda_function.lambda_handler(event, None)
saved_history = mock_save.call_args[0][1]
self.assertEqual(len(saved_history), 2)
self.assertEqual(saved_history[0]["role"], "user")
self.assertEqual(saved_history[0]["content"], "test question")
self.assertEqual(saved_history[1]["role"], "assistant")
self.assertEqual(saved_history[1]["content"], "Sure.")
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={"job": "software engineer"})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="Tailored answer.")
def test_user_facts_formatted_and_passed_to_llm(self, mock_llm, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="help me debug")
lambda_function.lambda_handler(event, None)
_, _, context_arg = mock_llm.call_args[0]
self.assertEqual(context_arg, "job: software engineer")
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="Answer.")
def test_correct_user_id_used(self, mock_llm, mock_get, mock_save, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="q", user_id="user-xyz")
lambda_function.lambda_handler(event, None)
mock_get.assert_called_once_with("user-xyz")
mock_save.assert_called_once_with("user-xyz", unittest.mock.ANY)
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[])
@patch("lambda_function.call_llm", return_value="OK.")
def test_session_stays_open_after_answer(self, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="anything")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_user_facts", return_value={})
@patch("lambda_function.save_history")
@patch("lambda_function.get_history", return_value=[
{"role": "user", "content": "msg"},
{"role": "assistant", "content": "reply"},
] * 10)
@patch("lambda_function.call_llm", return_value="OK.")
def test_long_history_still_works(self, *_):
event = make_event("IntentRequest", intent_name="AskClaudeIntent", query="latest question")
r = lambda_function.lambda_handler(event, None)
self.assertEqual(get_speech(r), "OK.")
# ══════════════════════════════════════════════════════════════════════════════
# 4. YesIntent / NoIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestYesNoIntent(unittest.TestCase):
# YesIntent → handle_continue_intent (delivers next pending chunk)
# NoIntent → clears pending chunks, keeps session open
@patch("lambda_function.save_pending_chunks")
@patch("lambda_function.get_pending_chunks", return_value=["Part two.", "Part three."])
def test_yes_delivers_next_chunk(self, *_):
event = make_event("IntentRequest", intent_name="AMAZON.YesIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("Part two", get_speech(r))
@patch("lambda_function.save_pending_chunks")
@patch("lambda_function.get_pending_chunks", return_value=["Part two.", "Part three."])
def test_yes_prompts_to_continue_when_more_chunks_remain(self, *_):
event = make_event("IntentRequest", intent_name="AMAZON.YesIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("continue", get_speech(r).lower())
@patch("lambda_function.clear_pending_chunks")
@patch("lambda_function.get_pending_chunks", return_value=["Last part."])
def test_yes_no_continue_prompt_on_last_chunk(self, *_):
event = make_event("IntentRequest", intent_name="AMAZON.YesIntent")
r = lambda_function.lambda_handler(event, None)
self.assertNotIn("continue", get_speech(r).lower())
@patch("lambda_function.get_pending_chunks", return_value=[])
def test_yes_with_no_pending_chunks_returns_graceful_message(self, *_):
event = make_event("IntentRequest", intent_name="AMAZON.YesIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("nothing more", get_speech(r).lower())
@patch("lambda_function.clear_pending_chunks")
def test_no_clears_pending_chunks(self, mock_clear):
event = make_event("IntentRequest", intent_name="AMAZON.NoIntent", user_id="u1")
lambda_function.lambda_handler(event, None)
mock_clear.assert_called_once_with("u1")
@patch("lambda_function.clear_pending_chunks")
def test_no_keeps_session_open(self, *_):
event = make_event("IntentRequest", intent_name="AMAZON.NoIntent")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 5. SetContextIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestSetContextIntent(unittest.TestCase):
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_merges_extracted_fact(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="I'm a nurse")
r = lambda_function.lambda_handler(event, None)
mock_merge.assert_called_once()
self.assertIn("Got it", get_speech(r))
@patch("lambda_function.merge_user_facts")
def test_empty_context_slot_returns_prompt(self, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent")
r = lambda_function.lambda_handler(event, None)
mock_merge.assert_not_called()
self.assertIn("didn't catch", get_speech(r))
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_saves_to_correct_user(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="I'm a pilot", user_id="user-abc")
lambda_function.lambda_handler(event, None)
self.assertEqual(mock_merge.call_args[0][0], "user-abc")
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_session_stays_open(self, *_):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="I like jazz")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_extracts_job_fact(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="I'm a software engineer")
lambda_function.lambda_handler(event, None)
fact = mock_merge.call_args[0][1]
self.assertEqual(fact.get("job"), "software engineer")
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_extracts_name_fact(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="my name is Nandana")
lambda_function.lambda_handler(event, None)
fact = mock_merge.call_args[0][1]
self.assertEqual(fact.get("name"), "Nandana")
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_extracts_location_fact(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="I live in New York")
lambda_function.lambda_handler(event, None)
fact = mock_merge.call_args[0][1]
self.assertEqual(fact.get("location"), "New York")
@patch("lambda_function.merge_user_facts")
@patch("lambda_function.get_user_facts", return_value={})
def test_unrecognised_utterance_stored_as_note(self, mock_get, mock_merge):
event = make_event("IntentRequest", intent_name="SetContextIntent", context_value="something random")
lambda_function.lambda_handler(event, None)
fact = mock_merge.call_args[0][1]
self.assertIn("note", fact)
# ══════════════════════════════════════════════════════════════════════════════
# 6. ClearContextIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestClearContextIntent(unittest.TestCase):
@patch("lambda_function.clear_user_facts")
def test_clears_all_facts(self, mock_clear):
event = make_event("IntentRequest", intent_name="ClearContextIntent")
r = lambda_function.lambda_handler(event, None)
mock_clear.assert_called_once_with("test-user-id")
self.assertIn("cleared", get_speech(r))
@patch("lambda_function.clear_user_facts")
def test_clears_correct_user(self, mock_clear):
event = make_event("IntentRequest", intent_name="ClearContextIntent", user_id="user-xyz")
lambda_function.lambda_handler(event, None)
mock_clear.assert_called_once_with("user-xyz")
@patch("lambda_function.clear_user_facts")
def test_session_stays_open(self, *_):
event = make_event("IntentRequest", intent_name="ClearContextIntent")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 6b. RecallContextIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestRecallContextIntent(unittest.TestCase):
@patch("lambda_function.get_user_facts", return_value={"name": "Nandana", "job": "engineer"})
def test_recalls_stored_facts(self, *_):
event = make_event("IntentRequest", intent_name="RecallContextIntent")
r = lambda_function.lambda_handler(event, None)
speech = get_speech(r)
self.assertIn("name", speech)
self.assertIn("Nandana", speech)
self.assertIn("job", speech)
self.assertIn("engineer", speech)
@patch("lambda_function.get_user_facts", return_value={})
def test_no_facts_returns_graceful_message(self, *_):
event = make_event("IntentRequest", intent_name="RecallContextIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("don't have any information", get_speech(r))
@patch("lambda_function.get_user_facts", return_value={"location": "New York"})
def test_correct_user_id_used(self, mock_get):
event = make_event("IntentRequest", intent_name="RecallContextIntent", user_id="u-recall")
lambda_function.lambda_handler(event, None)
mock_get.assert_called_once_with("u-recall")
@patch("lambda_function.get_user_facts", return_value={"name": "Nandana"})
def test_session_stays_open(self, *_):
event = make_event("IntentRequest", intent_name="RecallContextIntent")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 7. HelpIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestHelpIntent(unittest.TestCase):
def test_returns_help_text(self):
event = make_event("IntentRequest", intent_name="AMAZON.HelpIntent")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(len(get_speech(r)) > 0)
def test_session_stays_open(self):
event = make_event("IntentRequest", intent_name="AMAZON.HelpIntent")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 8. StopIntent / CancelIntent
# ══════════════════════════════════════════════════════════════════════════════
class TestStopIntent(unittest.TestCase):
def test_stop_ends_session(self):
event = make_event("IntentRequest", intent_name="AMAZON.StopIntent")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
def test_stop_says_goodbye(self):
event = make_event("IntentRequest", intent_name="AMAZON.StopIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("Goodbye", get_speech(r))
def test_cancel_ends_session(self):
event = make_event("IntentRequest", intent_name="AMAZON.CancelIntent")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
def test_cancel_says_goodbye(self):
event = make_event("IntentRequest", intent_name="AMAZON.CancelIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn("Goodbye", get_speech(r))
# ══════════════════════════════════════════════════════════════════════════════
# 9. FallbackIntent & unknown intents
# ══════════════════════════════════════════════════════════════════════════════
FALLBACK_RESPONSES = [
"How are you feeling about that?",
"Tell me more, I'm listening.",
"How did that make you feel?",
"What's on your mind?",
"I'm here. What would you like to talk about?",
"How are you feeling right now?",
"Want to talk about it?",
]
class TestFallbackIntent(unittest.TestCase):
def test_fallback_intent_returns_valid_response(self):
event = make_event("IntentRequest", intent_name="AMAZON.FallbackIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn(get_speech(r), FALLBACK_RESPONSES)
def test_unknown_intent_returns_fallback(self):
event = make_event("IntentRequest", intent_name="SomeRandomIntent")
r = lambda_function.lambda_handler(event, None)
self.assertIn(get_speech(r), FALLBACK_RESPONSES)
def test_fallback_session_stays_open(self):
event = make_event("IntentRequest", intent_name="AMAZON.FallbackIntent")
r = lambda_function.lambda_handler(event, None)
self.assertFalse(r["response"]["shouldEndSession"])
def test_fallback_is_randomised(self):
"""Over 50 calls at least 2 distinct responses should appear."""
event = make_event("IntentRequest", intent_name="AMAZON.FallbackIntent")
speeches = set()
for _ in range(50):
r = lambda_function.lambda_handler(event, None)
speeches.add(get_speech(r))
self.assertGreater(len(speeches), 1)
# ══════════════════════════════════════════════════════════════════════════════
# 10. SessionEndedRequest
# ══════════════════════════════════════════════════════════════════════════════
class TestSessionEndedRequest(unittest.TestCase):
def test_ends_session(self):
event = make_event("SessionEndedRequest")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
def test_user_initiated_reason(self):
event = make_event("SessionEndedRequest", session_reason="USER_INITIATED")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
def test_error_reason(self):
event = make_event("SessionEndedRequest", session_reason="ERROR")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
def test_exceeded_max_reprompts_reason(self):
event = make_event("SessionEndedRequest", session_reason="EXCEEDED_MAX_REPROMPTS")
r = lambda_function.lambda_handler(event, None)
self.assertTrue(r["response"]["shouldEndSession"])
# ══════════════════════════════════════════════════════════════════════════════
# 11. Unknown request type
# ══════════════════════════════════════════════════════════════════════════════
class TestUnknownRequestType(unittest.TestCase):
def test_unknown_type_returns_response(self):
event = make_event("LaunchRequest")
event["request"]["type"] = "WeirdRequestType"
r = lambda_function.lambda_handler(event, None)
self.assertIn("version", r)
# ══════════════════════════════════════════════════════════════════════════════
# 12. DynamoDB layer
# ══════════════════════════════════════════════════════════════════════════════
class TestDynamo(unittest.TestCase):
def setUp(self):
# Patch boto3 before importing dynamo so we never hit AWS
self.boto3_patcher = patch("boto3.resource")
self.mock_boto3 = self.boto3_patcher.start()
self.mock_table = MagicMock()
self.mock_boto3.return_value.Table.return_value = self.mock_table
# Force dynamo module to re-initialise its cached table reference
import dynamo
dynamo._table = None
self.dynamo = dynamo
def tearDown(self):
self.boto3_patcher.stop()
import dynamo
dynamo._table = None
# ── get_history ────────────────────────────────────────────────
def test_get_history_returns_list_when_item_exists(self):
history = [{"role": "user", "content": "hi"}]
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "history": history}}
result = self.dynamo.get_history("u1")
self.assertEqual(result, history)
def test_get_history_returns_empty_list_when_no_item(self):
self.mock_table.get_item.return_value = {}
result = self.dynamo.get_history("u1")
self.assertEqual(result, [])
def test_get_history_returns_empty_list_when_no_history_key(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1"}}
result = self.dynamo.get_history("u1")
self.assertEqual(result, [])
def test_get_history_calls_correct_user_id(self):
self.mock_table.get_item.return_value = {}
self.dynamo.get_history("my-special-user")
self.mock_table.get_item.assert_called_once_with(Key={"userId": "my-special-user"})
# ── save_history ───────────────────────────────────────────────
def test_save_history_calls_update_item(self):
history = [{"role": "user", "content": "hello"}]
self.dynamo.save_history("u1", history)
self.mock_table.update_item.assert_called_once()
def test_save_history_uses_correct_key(self):
self.dynamo.save_history("user-abc", [])
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertEqual(call_kwargs["Key"], {"userId": "user-abc"})
def test_save_history_passes_history_in_expression(self):
history = [{"role": "assistant", "content": "Hi!"}]
self.dynamo.save_history("u1", history)
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertEqual(call_kwargs["ExpressionAttributeValues"][":h"], history)
def test_save_empty_history(self):
self.dynamo.save_history("u1", [])
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertEqual(call_kwargs["ExpressionAttributeValues"][":h"], [])
def test_save_history_writes_ttl(self):
import time
before = int(time.time())
self.dynamo.save_history("u1", [])
call_kwargs = self.mock_table.update_item.call_args[1]
ttl_value = call_kwargs["ExpressionAttributeValues"][":t"]
# TTL should be roughly 7 days from now
self.assertGreater(ttl_value, before + 6 * 24 * 3600)
self.assertLess(ttl_value, before + 8 * 24 * 3600)
def test_save_history_prunes_before_writing(self):
import dynamo as dyn
# Build a history that exceeds MAX_HISTORY_TURNS
long_history = []
for i in range(dyn.MAX_HISTORY_TURNS + 5):
long_history.append({"role": "user", "content": f"q{i}"})
long_history.append({"role": "assistant", "content": f"a{i}"})
self.dynamo.save_history("u1", long_history)
call_kwargs = self.mock_table.update_item.call_args[1]
saved = call_kwargs["ExpressionAttributeValues"][":h"]
self.assertEqual(len(saved), dyn.MAX_HISTORY_TURNS * 2)
# ── prune_history ──────────────────────────────────────────────
def test_prune_history_returns_unchanged_when_within_limit(self):
history = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]
result = self.dynamo.prune_history(history, max_turns=10)
self.assertEqual(result, history)
def test_prune_history_trims_to_max_turns(self):
history = []
for i in range(25):
history.append({"role": "user", "content": f"q{i}"})
history.append({"role": "assistant", "content": f"a{i}"})
result = self.dynamo.prune_history(history, max_turns=20)
self.assertEqual(len(result), 40) # 20 turns * 2 messages
def test_prune_history_keeps_most_recent_turns(self):
history = []
for i in range(25):
history.append({"role": "user", "content": f"q{i}"})
history.append({"role": "assistant", "content": f"a{i}"})
result = self.dynamo.prune_history(history, max_turns=5)
self.assertEqual(result[0]["content"], "q20")
self.assertEqual(result[-1]["content"], "a24")
def test_prune_history_empty_list(self):
self.assertEqual(self.dynamo.prune_history([], max_turns=10), [])
def test_prune_history_exactly_at_limit(self):
history = []
for i in range(20):
history.append({"role": "user", "content": f"q{i}"})
history.append({"role": "assistant", "content": f"a{i}"})
result = self.dynamo.prune_history(history, max_turns=20)
self.assertEqual(len(result), 40)
# ── get_user_facts ─────────────────────────────────────────────
def test_get_user_facts_returns_dict_when_exists(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "userFacts": {"job": "chef"}}}
result = self.dynamo.get_user_facts("u1")
self.assertEqual(result, {"job": "chef"})
def test_get_user_facts_returns_empty_dict_when_no_item(self):
self.mock_table.get_item.return_value = {}
result = self.dynamo.get_user_facts("u1")
self.assertEqual(result, {})
def test_get_user_facts_returns_empty_dict_when_no_key(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1"}}
result = self.dynamo.get_user_facts("u1")
self.assertEqual(result, {})
# ── merge_user_facts ───────────────────────────────────────────
def test_merge_user_facts_merges_with_existing(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "userFacts": {"name": "Alice"}}}
self.dynamo.merge_user_facts("u1", {"job": "pilot"})
call_kwargs = self.mock_table.update_item.call_args[1]
saved = call_kwargs["ExpressionAttributeValues"][":f"]
self.assertEqual(saved, {"name": "Alice", "job": "pilot"})
def test_merge_user_facts_uses_correct_user_key(self):
self.mock_table.get_item.return_value = {}
self.dynamo.merge_user_facts("u-xyz", {"name": "Bob"})
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertEqual(call_kwargs["Key"], {"userId": "u-xyz"})
def test_merge_user_facts_overwrites_same_key(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "userFacts": {"job": "chef"}}}
self.dynamo.merge_user_facts("u1", {"job": "pilot"})
call_kwargs = self.mock_table.update_item.call_args[1]
saved = call_kwargs["ExpressionAttributeValues"][":f"]
self.assertEqual(saved["job"], "pilot")
# ── clear_user_facts ───────────────────────────────────────────
def test_clear_user_facts_calls_update_item(self):
self.dynamo.clear_user_facts("u1")
self.mock_table.update_item.assert_called_once()
def test_clear_user_facts_uses_remove_expression(self):
self.dynamo.clear_user_facts("u1")
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertIn("REMOVE", call_kwargs["UpdateExpression"])
def test_clear_user_facts_uses_correct_key(self):
self.dynamo.clear_user_facts("user-abc")
call_kwargs = self.mock_table.update_item.call_args[1]
self.assertEqual(call_kwargs["Key"], {"userId": "user-abc"})
# ── clear_user_fact (single key) ──────────────────────────────
def test_clear_user_fact_removes_specific_key(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "userFacts": {"name": "Alice", "job": "chef"}}}
self.dynamo.clear_user_fact("u1", "job")
call_kwargs = self.mock_table.update_item.call_args[1]
saved = call_kwargs["ExpressionAttributeValues"][":f"]
self.assertNotIn("job", saved)
self.assertIn("name", saved)
def test_clear_user_fact_noop_when_key_absent(self):
self.mock_table.get_item.return_value = {"Item": {"userId": "u1", "userFacts": {"name": "Alice"}}}
self.dynamo.clear_user_fact("u1", "job")
self.mock_table.update_item.assert_not_called()
# ── table name resolution ──────────────────────────────────────
def test_custom_table_name_from_env(self):
import dynamo
dynamo._table = None
with patch.dict(os.environ, {"DYNAMODB_TABLE": "MyCustomTable"}):
dynamo._table = None
self.mock_table.get_item.return_value = {}
dynamo.get_history("u1")
self.mock_boto3.return_value.Table.assert_called_with("MyCustomTable")
def test_default_table_name(self):
import dynamo
dynamo._table = None
env = {k: v for k, v in os.environ.items() if k != "DYNAMODB_TABLE"}
with patch.dict(os.environ, env, clear=True):
dynamo._table = None
self.mock_table.get_item.return_value = {}
dynamo.get_history("u1")
self.mock_boto3.return_value.Table.assert_called_with("AlexaConversationHistory")
# ══════════════════════════════════════════════════════════════════════════════
# 13. Groq provider
# ══════════════════════════════════════════════════════════════════════════════
class TestGroqProvider(unittest.TestCase):
def setUp(self):
# Re-import fresh with the test API key in place
import groq_provider
self.provider = groq_provider
def _make_groq_response(self, content="Hello from Groq."):
return {"choices": [{"message": {"content": content}}]}
@patch("urllib.request.urlopen")
def test_success_returns_content(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response("Groq says hi."))
result = self.provider.ask_llm("say hi", [], "")
self.assertEqual(result, "Groq says hi.")
@patch("urllib.request.urlopen")
def test_sends_user_message(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("what is AI", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
user_messages = [m for m in body["messages"] if m["role"] == "user"]
self.assertEqual(user_messages[-1]["content"], "what is AI")
@patch("urllib.request.urlopen")
def test_sends_conversation_history(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
history = [
{"role": "user", "content": "first question"},
{"role": "assistant", "content": "first answer"},
]
self.provider.ask_llm("second question", history, "")
body = json.loads(mock_open.call_args[0][0].data.decode())
# system + 2 history + 1 new user = 4 messages
self.assertEqual(len(body["messages"]), 4)
@patch("urllib.request.urlopen")
def test_system_prompt_included(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hello", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertEqual(body["messages"][0]["role"], "system")
@patch("urllib.request.urlopen")
def test_user_context_appended_to_system_prompt(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hello", [], "I am a teacher")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertIn("I am a teacher", body["messages"][0]["content"])
@patch("urllib.request.urlopen")
def test_empty_context_not_appended(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hello", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertNotIn("personal context", body["messages"][0]["content"])
@patch("urllib.request.urlopen")
def test_none_history_defaults_to_empty(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
result = self.provider.ask_llm("hi", None, None)
self.assertEqual(result, "Hello from Groq.")
@patch("urllib.request.urlopen")
def test_http_error_raises(self, mock_open):
import urllib.error
mock_open.side_effect = urllib.error.HTTPError(
url="https://api.groq.com",
code=429,
msg="Too Many Requests",
hdrs={},
fp=io.BytesIO(b'{"error":"rate limit"}'),
)
with self.assertRaises(urllib.error.HTTPError):
self.provider.ask_llm("hi", [], "")
def test_missing_api_key_raises(self):
with patch.dict(os.environ, {}, clear=True):
with self.assertRaises(ValueError):
self.provider.ask_llm("hi", [], "")
@patch("urllib.request.urlopen")
def test_authorization_header_sent(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hi", [], "")
req = mock_open.call_args[0][0]
self.assertIn("Authorization", req.headers)
self.assertTrue(req.headers["Authorization"].startswith("Bearer "))
@patch("urllib.request.urlopen")
def test_post_method_used(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hi", [], "")
req = mock_open.call_args[0][0]
self.assertEqual(req.get_method(), "POST")
@patch("urllib.request.urlopen")
def test_max_tokens_in_payload(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_groq_response())
self.provider.ask_llm("hi", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertIn("max_tokens", body)
# ══════════════════════════════════════════════════════════════════════════════
# 14. Gemini provider
# ══════════════════════════════════════════════════════════════════════════════
class TestGeminiProvider(unittest.TestCase):
def setUp(self):
import gemini_provider
self.provider = gemini_provider
def _make_gemini_response(self, content="Hello from Gemini."):
return {
"candidates": [
{"content": {"parts": [{"text": content}]}}
]
}
@patch("urllib.request.urlopen")
def test_success_returns_content(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_gemini_response("Gemini answer."))
result = self.provider.ask_llm("question", [], "")
self.assertEqual(result, "Gemini answer.")
@patch("urllib.request.urlopen")
def test_history_role_user_maps_correctly(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_gemini_response())
history = [{"role": "user", "content": "hi"}]
self.provider.ask_llm("follow up", history, "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertEqual(body["contents"][0]["role"], "user")
@patch("urllib.request.urlopen")
def test_history_role_assistant_maps_to_model(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_gemini_response())
history = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "hello"},
]
self.provider.ask_llm("next", history, "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertEqual(body["contents"][1]["role"], "model")
@patch("urllib.request.urlopen")
def test_user_message_appended_as_last_content(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_gemini_response())
self.provider.ask_llm("final question", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
last = body["contents"][-1]
self.assertEqual(last["role"], "user")
self.assertEqual(last["parts"][0]["text"], "final question")
@patch("urllib.request.urlopen")
def test_system_instruction_included(self, mock_open):
mock_open.return_value = make_urlopen_mock(self._make_gemini_response())
self.provider.ask_llm("hi", [], "")
body = json.loads(mock_open.call_args[0][0].data.decode())
self.assertIn("systemInstruction", body)