forked from GoogleCloudPlatform/BigQuery-Agent-Analytics-SDK
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
2622 lines (2327 loc) · 77.7 KB
/
test_cli.py
File metadata and controls
2622 lines (2327 loc) · 77.7 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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the bq-agent-sdk CLI."""
from datetime import datetime
from datetime import timezone
import json
import os
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from typer.testing import CliRunner
from bigquery_agent_analytics.cli import app
from bigquery_agent_analytics.evaluators import EvaluationReport
from bigquery_agent_analytics.evaluators import LLMAsJudge
from bigquery_agent_analytics.evaluators import SessionScore
from bigquery_agent_analytics.feedback import DriftReport
from bigquery_agent_analytics.feedback import QuestionDistribution
from bigquery_agent_analytics.insights import AggregatedInsights
from bigquery_agent_analytics.insights import InsightsReport
from bigquery_agent_analytics.insights import SessionMetadata
from bigquery_agent_analytics.trace import Span
from bigquery_agent_analytics.trace import Trace
runner = CliRunner()
_NOW = datetime(2026, 3, 12, 10, 0, 0, tzinfo=timezone.utc)
def _mock_trace():
return Trace(
trace_id="t1",
session_id="s1",
spans=[
Span(
event_type="LLM_REQUEST",
agent="bot",
timestamp=_NOW,
content={},
attributes={},
)
],
start_time=_NOW,
end_time=_NOW,
total_latency_ms=200.0,
)
def _mock_report(passed, total):
return EvaluationReport(
dataset="test",
evaluator_name="latency",
total_sessions=total,
passed_sessions=passed,
failed_sessions=total - passed,
created_at=_NOW,
session_scores=[
SessionScore(
session_id=f"s{i}",
scores={"latency": 0.9 if i < passed else 0.3},
passed=i < passed,
)
for i in range(total)
],
)
# ------------------------------------------------------------------ #
# doctor #
# ------------------------------------------------------------------ #
class TestDoctor:
@patch("bigquery_agent_analytics.cli._build_client")
def test_doctor_json(self, mock_build):
client = MagicMock()
client.doctor.return_value = {
"status": "OK",
"event_count": 100,
}
mock_build.return_value = client
result = runner.invoke(
app,
[
"doctor",
"--project-id=proj",
"--dataset-id=ds",
],
)
assert result.exit_code == 0
parsed = json.loads(result.output)
assert parsed["status"] == "OK"
assert parsed["event_count"] == 100
@patch("bigquery_agent_analytics.cli._build_client")
def test_doctor_error_exit_2(self, mock_build):
mock_build.side_effect = RuntimeError("connection failed")
result = runner.invoke(
app,
[
"doctor",
"--project-id=proj",
"--dataset-id=ds",
],
)
assert result.exit_code == 2
# ------------------------------------------------------------------ #
# get-trace #
# ------------------------------------------------------------------ #
class TestGetTrace:
@patch("bigquery_agent_analytics.cli._build_client")
def test_get_trace_by_session_id(self, mock_build):
client = MagicMock()
client.get_session_trace.return_value = _mock_trace()
mock_build.return_value = client
result = runner.invoke(
app,
[
"get-trace",
"--project-id=proj",
"--dataset-id=ds",
"--session-id=s1",
],
)
assert result.exit_code == 0
parsed = json.loads(result.output)
assert parsed["trace_id"] == "t1"
assert parsed["session_id"] == "s1"
client.get_session_trace.assert_called_once_with("s1")
@patch("bigquery_agent_analytics.cli._build_client")
def test_get_trace_by_trace_id(self, mock_build):
client = MagicMock()
client.get_trace.return_value = _mock_trace()
mock_build.return_value = client
result = runner.invoke(
app,
[
"get-trace",
"--project-id=proj",
"--dataset-id=ds",
"--trace-id=t1",
],
)
assert result.exit_code == 0
parsed = json.loads(result.output)
assert parsed["trace_id"] == "t1"
client.get_trace.assert_called_once_with("t1")
def test_get_trace_missing_id_exit_2(self):
result = runner.invoke(
app,
[
"get-trace",
"--project-id=proj",
"--dataset-id=ds",
],
)
assert result.exit_code == 2
@patch("bigquery_agent_analytics.cli._build_client")
def test_get_trace_text_format(self, mock_build):
client = MagicMock()
client.get_session_trace.return_value = _mock_trace()
mock_build.return_value = client
result = runner.invoke(
app,
[
"get-trace",
"--project-id=proj",
"--dataset-id=ds",
"--session-id=s1",
"--format=text",
],
)
assert result.exit_code == 0
# Text format for Trace uses render() which includes trace_id
assert "t1" in result.output
# ------------------------------------------------------------------ #
# evaluate #
# ------------------------------------------------------------------ #
class TestEvaluate:
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_latency_pass(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--threshold=5000",
],
)
assert result.exit_code == 0
parsed = json.loads(result.output)
assert parsed["total_sessions"] == 10
assert parsed["passed_sessions"] == 10
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_on_failure(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(7, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 1
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_emits_failure_lines(self, mock_build):
"""--exit-code failure path emits one FAIL line per failing session.
Regression guard: prior output did not point the reader at which
threshold regressed and by how much. The new path stashes the raw
observed value + budget in ``SessionScore.details`` and prints
them on stderr before raising Exit(code=1).
"""
report = EvaluationReport(
dataset="test",
evaluator_name="latency_evaluator",
total_sessions=2,
passed_sessions=1,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="good",
scores={"latency": 1.0},
passed=True,
details={
"metric_latency": {
"observed": 1200,
"budget": 5000,
"threshold": 1.0,
"score": 1.0,
"passed": True,
}
},
),
SessionScore(
session_id="bad",
scores={"latency": 0.0},
passed=False,
details={
"metric_latency": {
"observed": 7500,
"budget": 5000,
"threshold": 1.0,
"score": 0.0,
"passed": False,
}
},
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
assert "--exit-code" in combined
assert "1 session(s) failed" in combined
assert "FAIL session=bad" in combined
assert "metric=latency" in combined
assert "observed=7500" in combined
assert "budget=5000" in combined
# Passing sessions must not emit a FAIL line.
assert "session=good" not in combined
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_emits_fallback_for_custom_metric(
self, mock_build
):
"""Custom metric without observed/budget still gets a FAIL line.
Regression guard: previously the emitter only printed a line when
the score was exactly 0.0, so a custom ``add_metric(threshold=0.7)``
or LLM judge scoring 0.6 for a failing session silently produced
only the summary header. That left CI logs unhelpful.
"""
report = EvaluationReport(
dataset="test",
evaluator_name="custom_eval",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"helpfulness": 0.6},
passed=False,
details={
"metric_helpfulness": {
"observed": None,
"budget": None,
"threshold": 0.7,
"score": 0.6,
"passed": False,
}
},
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
assert "FAIL session=bad" in combined
assert "metric=helpfulness" in combined
assert "score=0.6" in combined
assert "threshold=0.7" in combined
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_emits_fallback_with_no_details(self, mock_build):
"""Failing session with empty details still emits a FAIL line.
Safety-net guard: if an upstream evaluator doesn't populate
per-metric details, we still name the session and metric rather
than printing only the summary header.
"""
report = EvaluationReport(
dataset="test",
evaluator_name="legacy_eval",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"legacy_metric": 0.3},
passed=False,
details={},
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
assert "FAIL session=bad" in combined
assert "metric=legacy_metric" in combined
assert "score=0.3" in combined
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_llm_judge_emits_feedback_snippet(
self, mock_build
):
"""LLM-judge failures expose ``SessionScore.llm_feedback`` in the
FAIL line as a bounded ``feedback="..."`` snippet.
Without this, post #2's deterministic FAIL output story carries
over to LLM-judge, but the differentiator vs. a hand-rolled judge
("the score is *explained*") has nothing visible in CI logs.
"""
report = EvaluationReport(
dataset="test",
evaluator_name="correctness_judge",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"correctness": 0.3},
passed=False,
details={},
llm_feedback=(
"The agent confirmed a booking but the booking"
" tool never ran for that session."
),
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
"--criterion=correctness",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
# Existing fields still present.
assert "FAIL session=bad" in combined
assert "metric=correctness" in combined
assert "score=0.3" in combined
# Feedback snippet appears, quoted, with the actual justification.
assert 'feedback="' in combined
assert "booking tool never ran" in combined
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_llm_judge_truncates_long_feedback(
self, mock_build
):
"""Justifications longer than the snippet bound are truncated with U+2026."""
long_feedback = "word " * 200 # ~1000 chars
report = EvaluationReport(
dataset="test",
evaluator_name="correctness_judge",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"correctness": 0.0},
passed=False,
details={},
llm_feedback=long_feedback,
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
# Look at the FAIL line itself: feedback="...". The snippet stays
# under the configured cap (120 chars between the quotes).
fail_line = next(
line for line in combined.splitlines() if line.startswith(" FAIL")
)
assert 'feedback="' in fail_line
quoted = fail_line.split('feedback="', 1)[1].rsplit('"', 1)[0]
assert len(quoted) <= 120
assert quoted.endswith("\u2026")
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_collapses_newlines_in_feedback(self, mock_build):
"""Multi-line judge feedback collapses to a single CI log line."""
report = EvaluationReport(
dataset="test",
evaluator_name="correctness_judge",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"correctness": 0.2},
passed=False,
details={},
llm_feedback="Line one.\nLine two.\n\nLine three.",
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
fail_line = next(
line for line in combined.splitlines() if line.startswith(" FAIL")
)
quoted = fail_line.split('feedback="', 1)[1].rsplit('"', 1)[0]
assert "Line one. Line two. Line three." == quoted
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_code_metric_omits_feedback(self, mock_build):
"""Code-based metrics leave llm_feedback empty -> no feedback field."""
report = EvaluationReport(
dataset="test",
evaluator_name="latency_evaluator",
total_sessions=1,
passed_sessions=0,
failed_sessions=1,
created_at=_NOW,
session_scores=[
SessionScore(
session_id="bad",
scores={"latency": 0.0},
passed=False,
details={
"metric_latency": {
"observed": 7000,
"budget": 5000,
"threshold": 1.0,
"score": 0.0,
"passed": False,
}
},
llm_feedback=None,
),
],
)
client = MagicMock()
client.evaluate.return_value = report
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 1
combined = (result.stderr or "") + (result.output or "")
assert "observed=7000" in combined
assert "budget=5000" in combined
# No feedback field should be emitted for code-based metrics.
assert "feedback=" not in combined
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_exit_code_on_pass(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=latency",
"--exit-code",
],
)
assert result.exit_code == 0
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_with_filter_args(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(5, 5)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=error_rate",
"--threshold=0.1",
"--agent-id=bot",
"--last=1h",
"--limit=50",
],
)
assert result.exit_code == 0
# Verify the filter was passed
call_kwargs = client.evaluate.call_args
filters = call_kwargs.kwargs.get("filters") or call_kwargs[1].get("filters")
assert filters.agent_id == "bot"
assert filters.limit == 50
assert filters.start_time is not None
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_llm_judge(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(8, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
"--criterion=correctness",
"--threshold=0.7",
],
)
assert result.exit_code == 0
call_args = client.evaluate.call_args
ev = call_args.kwargs.get("evaluator") or call_args[1].get("evaluator")
assert isinstance(ev, LLMAsJudge)
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_text_format(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--format=text",
],
)
assert result.exit_code == 0
# Text format uses .summary() which mentions evaluator name
assert "latency" in result.output
def test_evaluate_unknown_evaluator(self):
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=bogus",
],
)
assert result.exit_code == 2
def test_evaluate_unknown_criterion(self):
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
"--criterion=bogus",
],
)
assert result.exit_code == 2
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_strict_flag(self, mock_build):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--strict",
],
)
assert result.exit_code == 0
call_kwargs = client.evaluate.call_args
assert call_kwargs.kwargs.get("strict") is True
@patch("bigquery_agent_analytics.cli._build_client")
def test_evaluate_infra_error_exit_2(self, mock_build):
client = MagicMock()
client.evaluate.side_effect = RuntimeError("BQ timeout")
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
],
)
assert result.exit_code == 2
class TestFormatFeedbackSnippet:
"""Direct unit tests for _format_feedback_snippet."""
def test_none_input_returns_none(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
assert _format_feedback_snippet(None) is None
def test_empty_input_returns_none(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
assert _format_feedback_snippet("") is None
assert _format_feedback_snippet(" \n\t ") is None
def test_short_input_passes_through_unchanged(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
assert _format_feedback_snippet("Short and useful.") == "Short and useful."
def test_collapses_internal_whitespace_runs(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
out = _format_feedback_snippet("First.\n\n Second.\tThird.")
assert out == "First. Second. Third."
def test_truncates_with_ellipsis_at_max_chars(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
text = "x" * 500
out = _format_feedback_snippet(text, max_chars=120)
assert len(out) == 120
assert out.endswith("\u2026")
def test_max_chars_param_respected(self):
from bigquery_agent_analytics.cli import _format_feedback_snippet
out = _format_feedback_snippet("y" * 200, max_chars=50)
assert len(out) == 50
assert out.endswith("\u2026")
# ------------------------------------------------------------------ #
# env var fallback #
# ------------------------------------------------------------------ #
class TestEnvVars:
@patch("bigquery_agent_analytics.cli._build_client")
def test_env_var_project_and_dataset(self, mock_build):
client = MagicMock()
client.doctor.return_value = {"status": "OK"}
mock_build.return_value = client
result = runner.invoke(
app,
["doctor"],
env={
"BQ_AGENT_PROJECT": "env-proj",
"BQ_AGENT_DATASET": "env-ds",
},
)
assert result.exit_code == 0
mock_build.assert_called_once()
call_args = mock_build.call_args
assert call_args[1].get("project_id") or call_args[0][0] in ("env-proj",)
# ------------------------------------------------------------------ #
# all evaluator types #
# ------------------------------------------------------------------ #
class TestAllEvaluators:
@pytest.mark.parametrize(
"name",
[
"latency",
"error_rate",
"turn_count",
"token_efficiency",
"ttft",
"cost",
],
)
@patch("bigquery_agent_analytics.cli._build_client")
def test_code_evaluator(self, mock_build, name):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
f"--evaluator={name}",
"--threshold=100",
],
)
assert result.exit_code == 0
@pytest.mark.parametrize(
"criterion",
["correctness", "hallucination", "sentiment"],
)
@patch("bigquery_agent_analytics.cli._build_client")
def test_llm_judge_criteria(self, mock_build, criterion):
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
f"--criterion={criterion}",
"--threshold=0.5",
],
)
assert result.exit_code == 0
# ------------------------------------------------------------------ #
# default thresholds #
# ------------------------------------------------------------------ #
class TestDefaultThresholds:
@pytest.mark.parametrize(
"name",
[
"latency",
"error_rate",
"turn_count",
"token_efficiency",
"ttft",
"cost",
],
)
@patch("bigquery_agent_analytics.cli._build_client")
def test_code_evaluator_uses_sdk_default(self, mock_build, name):
"""Omitting --threshold should use the SDK's built-in default."""
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
f"--evaluator={name}",
],
)
assert result.exit_code == 0
@pytest.mark.parametrize(
"criterion",
["correctness", "hallucination", "sentiment"],
)
@patch("bigquery_agent_analytics.cli._build_client")
def test_llm_judge_uses_sdk_default(self, mock_build, criterion):
"""Omitting --threshold for llm-judge should use 0.5, not 5000."""
client = MagicMock()
client.evaluate.return_value = _mock_report(10, 10)
mock_build.return_value = client
result = runner.invoke(
app,
[
"evaluate",
"--project-id=proj",
"--dataset-id=ds",
"--evaluator=llm-judge",
f"--criterion={criterion}",
],
)
assert result.exit_code == 0
# ------------------------------------------------------------------ #
# Helpers for v1.1 commands #
# ------------------------------------------------------------------ #
def _mock_insights():
meta = SessionMetadata(
session_id="s1",
event_count=10,
tool_calls=3,
tool_errors=0,
llm_calls=5,
turn_count=2,
total_latency_ms=1200.0,
avg_latency_ms=600.0,
agents_used=["bot"],
tools_used=["search"],
has_error=False,
hitl_events=0,
state_changes=0,
start_time=_NOW,
end_time=_NOW,
)
return InsightsReport(
created_at=_NOW,
session_metadata=[meta],
aggregated=AggregatedInsights(
total_sessions=1,
success_rate=1.0,
avg_effectiveness=0.9,
avg_latency_ms=1200.0,
avg_turns=2.0,
error_rate=0.0,
),
executive_summary="All good.",
)
def _mock_drift():
return DriftReport(
coverage_percentage=0.85,
total_golden=100,
total_production=200,
)
def _mock_distribution():