-
-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathtest_data_reader.py
More file actions
1863 lines (1519 loc) · 71.9 KB
/
test_data_reader.py
File metadata and controls
1863 lines (1519 loc) · 71.9 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 tests for data/reader.py module.
Tests the data loading and processing functions to achieve 80%+ coverage.
Covers file reading, data filtering, mapping, and error handling scenarios.
"""
import json
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from unittest.mock import Mock, mock_open, patch
import pytest
from claude_monitor.core.models import CostMode, UsageEntry
from claude_monitor.core.pricing import PricingCalculator
from claude_monitor.data.reader import (
UsageEntryMapper,
_create_unique_hash, # type: ignore[misc]
_find_jsonl_files, # type: ignore[misc]
_map_to_usage_entry, # type: ignore[misc]
_process_single_file, # type: ignore[misc]
_should_process_entry, # type: ignore[misc]
_update_processed_hashes, # type: ignore[misc]
load_all_raw_entries,
load_usage_entries,
)
# Note: RawJSONEntry type is referenced in comments but not directly used
# since test data uses dict literals with type ignore comments
from claude_monitor.utils.time_utils import TimezoneHandler
class TestLoadUsageEntries:
"""Test the main load_usage_entries function."""
@patch("claude_monitor.data.reader._find_jsonl_files")
@patch("claude_monitor.data.reader._process_single_file")
def test_load_usage_entries_basic(
self, mock_process_file: Mock, mock_find_files: Mock
) -> None:
mock_find_files.return_value = [
Path("/test/file1.jsonl"),
Path("/test/file2.jsonl"),
]
sample_entry = UsageEntry(
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
input_tokens=100,
output_tokens=50,
model="claude-3-haiku",
)
mock_process_file.side_effect = [
([sample_entry], [{"raw": "data1"}]),
([], [{"raw": "data2"}]),
]
entries, raw_data = load_usage_entries(
data_path="/test/path",
hours_back=24,
mode=CostMode.CALCULATED,
include_raw=True,
)
assert len(entries) == 1
assert entries[0] == sample_entry
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 2
assert raw_data == [{"raw": "data1"}, {"raw": "data2"}]
mock_find_files.assert_called_once()
assert mock_process_file.call_count == 2
@patch("claude_monitor.data.reader._find_jsonl_files")
def test_load_usage_entries_no_files(self, mock_find_files: Mock) -> None:
mock_find_files.return_value = list[Path]()
entries, raw_data = load_usage_entries(include_raw=True)
assert entries == []
assert raw_data is None
@patch("claude_monitor.data.reader._find_jsonl_files")
@patch("claude_monitor.data.reader._process_single_file")
def test_load_usage_entries_without_raw(
self, mock_process_file: Mock, mock_find_files: Mock
) -> None:
mock_find_files.return_value = [Path("/test/file1.jsonl")]
sample_entry = UsageEntry(
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
input_tokens=100,
output_tokens=50,
model="claude-3-haiku",
)
mock_process_file.return_value = ([sample_entry], None)
entries, raw_data = load_usage_entries(include_raw=False)
assert len(entries) == 1
assert raw_data is None
@patch("claude_monitor.data.reader._find_jsonl_files")
@patch("claude_monitor.data.reader._process_single_file")
def test_load_usage_entries_sorting(
self, mock_process_file: Mock, mock_find_files: Mock
) -> None:
"""Test that entries are sorted by timestamp."""
mock_find_files.return_value = [Path("/test/file1.jsonl")]
entry1 = UsageEntry(
timestamp=datetime(2024, 1, 1, 14, 0, tzinfo=timezone.utc),
input_tokens=100,
output_tokens=50,
model="claude-3-haiku",
)
entry2 = UsageEntry(
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
input_tokens=200,
output_tokens=75,
model="claude-3-sonnet",
)
mock_process_file.return_value = ([entry1, entry2], None)
entries, _ = load_usage_entries()
assert len(entries) == 2
assert entries[0] == entry2
assert entries[1] == entry1
@patch("claude_monitor.data.reader._find_jsonl_files")
@patch("claude_monitor.data.reader._process_single_file")
def test_load_usage_entries_with_cutoff_time(
self, mock_process_file: Mock, mock_find_files: Mock
) -> None:
mock_find_files.return_value = [Path("/test/file1.jsonl")]
mock_process_file.return_value = ([], None)
with patch("claude_monitor.data.reader.datetime") as mock_datetime:
current_time = datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc)
mock_datetime.now.return_value = current_time
load_usage_entries(hours_back=24)
expected_cutoff = current_time - timedelta(hours=24)
mock_process_file.assert_called_once()
call_args = mock_process_file.call_args[0]
assert call_args[2] == expected_cutoff
def test_load_usage_entries_default_path(self) -> None:
with patch("claude_monitor.data.reader._find_jsonl_files") as mock_find:
mock_find.return_value = list[Path]()
load_usage_entries()
call_args = mock_find.call_args[0]
path_str = str(call_args[0])
assert ".claude/projects" in path_str
class TestLoadAllRawEntries:
"""Test the load_all_raw_entries function."""
@patch("claude_monitor.data.reader._find_jsonl_files")
def test_load_all_raw_entries_basic(self, mock_find_files: Mock) -> None:
test_file = Path("/test/file.jsonl")
mock_find_files.return_value = [test_file]
raw_data = [
{"type": "user", "content": "Hello"},
{"type": "assistant", "content": "Hi there"},
]
jsonl_content = "\n".join(json.dumps(item) for item in raw_data)
with patch("builtins.open", mock_open(read_data=jsonl_content)):
result = load_all_raw_entries("/test/path")
assert len(result) == 2
assert result == raw_data
@patch("claude_monitor.data.reader._find_jsonl_files")
def test_load_all_raw_entries_with_empty_lines(self, mock_find_files: Mock) -> None:
test_file = Path("/test/file.jsonl")
mock_find_files.return_value = [test_file]
jsonl_content = '{"valid": "data"}\n\n \n{"more": "data"}\n'
with patch("builtins.open", mock_open(read_data=jsonl_content)):
result = load_all_raw_entries("/test/path")
assert len(result) == 2
assert result[0] == {"valid": "data"}
assert result[1] == {"more": "data"}
@patch("claude_monitor.data.reader._find_jsonl_files")
def test_load_all_raw_entries_with_invalid_json(
self, mock_find_files: Mock
) -> None:
test_file = Path("/test/file.jsonl")
mock_find_files.return_value = [test_file]
jsonl_content = '{"valid": "data"}\ninvalid json\n{"more": "data"}\n'
with patch("builtins.open", mock_open(read_data=jsonl_content)):
result = load_all_raw_entries("/test/path")
assert len(result) == 2
assert result[0] == {"valid": "data"}
assert result[1] == {"more": "data"}
@patch("claude_monitor.data.reader._find_jsonl_files")
def test_load_all_raw_entries_file_error(self, mock_find_files: Mock) -> None:
test_file = Path("/test/file.jsonl")
mock_find_files.return_value = [test_file]
with patch("builtins.open", side_effect=OSError("File not found")):
with patch("claude_monitor.data.reader.logger") as mock_logger:
result = load_all_raw_entries("/test/path")
assert result == []
mock_logger.exception.assert_called()
def test_load_all_raw_entries_default_path(self) -> None:
with patch("claude_monitor.data.reader._find_jsonl_files") as mock_find:
mock_find.return_value = list[Path]()
load_all_raw_entries()
call_args = mock_find.call_args[0]
path_str = str(call_args[0])
assert ".claude/projects" in path_str
class TestFindJsonlFiles:
"""Test the _find_jsonl_files function."""
def test_find_jsonl_files_nonexistent_path(self) -> None:
with patch("claude_monitor.data.reader.logger") as mock_logger:
result = _find_jsonl_files(Path("/nonexistent/path"))
assert result == []
mock_logger.warning.assert_called()
def test_find_jsonl_files_existing_path(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
(temp_path / "file1.jsonl").touch()
(temp_path / "file2.jsonl").touch()
(temp_path / "file3.txt").touch() # Non-JSONL file
# Create subdirectory with JSONL file
subdir = temp_path / "subdir"
subdir.mkdir()
(subdir / "file4.jsonl").touch()
result = _find_jsonl_files(temp_path)
jsonl_files = [f.name for f in result]
assert "file1.jsonl" in jsonl_files
assert "file2.jsonl" in jsonl_files
assert "file4.jsonl" in jsonl_files
assert len(result) == 3
class TestProcessSingleFile:
"""Test the _process_single_file function."""
@pytest.fixture
def mock_components(self) -> tuple[Mock, Mock]:
timezone_handler = Mock(spec=TimezoneHandler)
pricing_calculator = Mock(spec=PricingCalculator)
return timezone_handler, pricing_calculator
def test_process_single_file_valid_data(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
sample_data = [
{
"timestamp": "2024-01-01T12:00:00Z",
"message": {"usage": {"input_tokens": 100, "output_tokens": 50}},
"model": "claude-3-haiku",
"message_id": "msg_1",
"request_id": "req_1",
}
]
jsonl_content = "\n".join(json.dumps(item) for item in sample_data)
test_file = Path("/test/file.jsonl")
sample_entry = UsageEntry(
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
input_tokens=100,
output_tokens=50,
model="claude-3-haiku",
)
with (
patch("builtins.open", mock_open(read_data=jsonl_content)),
patch(
"claude_monitor.data.reader._should_process_entry", return_value=True
),
patch(
"claude_monitor.data.reader._map_to_usage_entry",
return_value=sample_entry,
),
patch("claude_monitor.data.reader._update_processed_hashes"),
):
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None, # cutoff_time
set(), # processed_hashes
True, # include_raw
timezone_handler,
pricing_calculator,
)
assert len(entries) == 1
assert entries[0] == sample_entry
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 1
assert raw_data[0] == sample_data[0]
def test_process_single_file_without_raw(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
sample_data = [{"timestamp": "2024-01-01T12:00:00Z", "input_tokens": 100}]
jsonl_content = json.dumps(sample_data[0])
test_file = Path("/test/file.jsonl")
sample_entry = UsageEntry(
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
input_tokens=100,
output_tokens=50,
model="claude-3-haiku",
)
with (
patch("builtins.open", mock_open(read_data=jsonl_content)),
patch(
"claude_monitor.data.reader._should_process_entry", return_value=True
),
patch(
"claude_monitor.data.reader._map_to_usage_entry",
return_value=sample_entry,
),
patch("claude_monitor.data.reader._update_processed_hashes"),
):
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None,
set(),
False,
timezone_handler,
pricing_calculator,
)
assert len(entries) == 1
assert raw_data is None
def test_process_single_file_filtered_entries(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler: Mock
pricing_calculator: Mock
timezone_handler, pricing_calculator = mock_components
sample_data = [{"timestamp": "2024-01-01T12:00:00Z", "input_tokens": 100}]
jsonl_content = json.dumps(sample_data[0])
test_file = Path("/test/file.jsonl")
with (
patch("builtins.open", mock_open(read_data=jsonl_content)),
patch(
"claude_monitor.data.reader._should_process_entry", return_value=False
),
):
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None,
set(),
True,
timezone_handler,
pricing_calculator,
)
assert len(entries) == 0
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 0
def test_process_single_file_invalid_json(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
jsonl_content = 'invalid json\n{"valid": "data"}'
test_file = Path("/test/file.jsonl")
with (
patch("builtins.open", mock_open(read_data=jsonl_content)),
patch(
"claude_monitor.data.reader._should_process_entry", return_value=True
),
patch("claude_monitor.data.reader._map_to_usage_entry", return_value=None),
):
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None,
set(),
True,
timezone_handler,
pricing_calculator,
)
assert len(entries) == 0
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 1
def test_process_single_file_read_error(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
test_file = Path("/test/nonexistent.jsonl")
with patch("builtins.open", side_effect=OSError("File not found")):
with patch("claude_monitor.data.reader.report_file_error") as mock_report:
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None,
set(),
True,
timezone_handler,
pricing_calculator,
)
assert entries == []
assert raw_data is None
mock_report.assert_called_once()
def test_process_single_file_mapping_failure(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
sample_data = [{"timestamp": "2024-01-01T12:00:00Z", "input_tokens": 100}]
jsonl_content = json.dumps(sample_data[0])
test_file = Path("/test/file.jsonl")
with (
patch("builtins.open", mock_open(read_data=jsonl_content)),
patch(
"claude_monitor.data.reader._should_process_entry", return_value=True
),
patch("claude_monitor.data.reader._map_to_usage_entry", return_value=None),
):
entries, raw_data = _process_single_file(
test_file,
CostMode.AUTO,
None,
set(),
True,
timezone_handler,
pricing_calculator,
)
assert len(entries) == 0
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 1
class TestShouldProcessEntry:
"""Test the _should_process_entry function."""
@pytest.fixture
def timezone_handler(self) -> Mock:
return Mock(spec=TimezoneHandler)
def test_should_process_entry_no_cutoff_no_hash(
self, timezone_handler: Mock
) -> None:
data = {"timestamp": "2024-01-01T12:00:00Z", "message_id": "msg_1"}
with patch(
"claude_monitor.data.reader._create_unique_hash", return_value="hash_1"
):
# Test with mock data dict - using dict literal for test data simplicity
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(data, None, set(), timezone_handler) # type: ignore[arg-type] # Mock test data # type: ignore[arg-type] # Mock test data
assert result is True
def test_should_process_entry_with_time_filter_pass(
self, timezone_handler: Mock
) -> None:
data = {"timestamp": "2024-01-01T12:00:00Z"}
cutoff_time = datetime(2024, 1, 1, 10, 0, tzinfo=timezone.utc)
with patch(
"claude_monitor.data.reader.TimestampProcessor"
) as mock_processor_class:
mock_processor = Mock()
mock_processor.parse_timestamp.return_value = datetime(
2024, 1, 1, 12, 0, tzinfo=timezone.utc
)
mock_processor_class.return_value = mock_processor
with patch(
"claude_monitor.data.reader._create_unique_hash", return_value="hash_1"
):
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(
data, # type: ignore[arg-type] # Mock test data
cutoff_time,
set(),
timezone_handler,
)
assert result is True
def test_should_process_entry_with_time_filter_fail(
self, timezone_handler: Mock
) -> None:
data = {"timestamp": "2024-01-01T08:00:00Z"}
cutoff_time = datetime(2024, 1, 1, 10, 0, tzinfo=timezone.utc)
with patch(
"claude_monitor.data.reader.TimestampProcessor"
) as mock_processor_class:
mock_processor = Mock()
mock_processor.parse_timestamp.return_value = datetime(
2024, 1, 1, 8, 0, tzinfo=timezone.utc
)
mock_processor_class.return_value = mock_processor
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(data, cutoff_time, set(), timezone_handler) # type: ignore[arg-type] # Mock test data
assert result is False
def test_should_process_entry_with_duplicate_hash(
self, timezone_handler: Mock
) -> None:
data = {"message_id": "msg_1", "request_id": "req_1"}
processed_hashes = {"msg_1:req_1"}
with patch(
"claude_monitor.data.reader._create_unique_hash", return_value="msg_1:req_1"
):
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(
data, # type: ignore[arg-type] # Mock test data
None,
processed_hashes,
timezone_handler,
)
assert result is False
def test_should_process_entry_no_timestamp(self, timezone_handler: Mock) -> None:
data = {"message_id": "msg_1"}
cutoff_time = datetime(2024, 1, 1, 10, 0, tzinfo=timezone.utc)
with patch(
"claude_monitor.data.reader._create_unique_hash", return_value="hash_1"
):
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(data, cutoff_time, set(), timezone_handler) # type: ignore[arg-type] # Mock test data
assert result is True
def test_should_process_entry_invalid_timestamp(
self, timezone_handler: Mock
) -> None:
data = {"timestamp": "invalid", "message_id": "msg_1"}
cutoff_time = datetime(2024, 1, 1, 10, 0, tzinfo=timezone.utc)
with patch(
"claude_monitor.core.data_processors.TimestampProcessor"
) as mock_processor_class:
mock_processor = Mock()
mock_processor.parse_timestamp.return_value = None
mock_processor_class.return_value = mock_processor
with patch(
"claude_monitor.data.reader._create_unique_hash", return_value="hash_1"
):
# Test with mock data dict - using dict literal for test data simplicity
result = _should_process_entry(
data, # type: ignore[arg-type] # Mock test data
cutoff_time,
set(),
timezone_handler,
)
assert result is True
class TestCreateUniqueHash:
"""Test the _create_unique_hash function."""
def test_create_unique_hash_with_message_id_and_request_id(self) -> None:
data = {"message_id": "msg_123", "request_id": "req_456"}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result == "msg_123:req_456"
def test_create_unique_hash_with_nested_message_id(self) -> None:
data = {"message": {"id": "msg_123"}, "requestId": "req_456"}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result == "msg_123:req_456"
def test_create_unique_hash_missing_message_id(self) -> None:
data = {"request_id": "req_456"}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result is None
def test_create_unique_hash_missing_request_id(self) -> None:
data = {"message_id": "msg_123"}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result is None
def test_create_unique_hash_invalid_message_structure(self) -> None:
data = {"message": "not_a_dict", "request_id": "req_456"}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result is None
def test_create_unique_hash_empty_data(self) -> None:
data: dict[str, str] = {}
# Test with mock data dict - using dict literal for test data simplicity
result = _create_unique_hash(data) # type: ignore[arg-type] # Mock test data
assert result is None
class TestUpdateProcessedHashes:
"""Test the _update_processed_hashes function."""
def test_update_processed_hashes_valid_hash(self) -> None:
data = {"message_id": "msg_123", "request_id": "req_456"}
processed_hashes = set[str]()
with patch(
"claude_monitor.data.reader._create_unique_hash",
return_value="msg_123:req_456",
):
# Test with mock data dict and set - using dict literal for test data simplicity
_update_processed_hashes(data, processed_hashes) # type: ignore[arg-type] # Mock test data
assert "msg_123:req_456" in processed_hashes
def test_update_processed_hashes_no_hash(self) -> None:
data = {"some": "data"}
processed_hashes = set[str]()
with patch("claude_monitor.data.reader._create_unique_hash", return_value=None):
# Test with mock data dict and set - using dict literal for test data simplicity
_update_processed_hashes(data, processed_hashes) # type: ignore[arg-type] # Mock test data
assert len(processed_hashes) == 0
class TestMapToUsageEntry:
"""Test the _map_to_usage_entry function."""
@pytest.fixture
def mock_components(self) -> tuple[Mock, Mock]:
timezone_handler = Mock(spec=TimezoneHandler)
pricing_calculator = Mock(spec=PricingCalculator)
return timezone_handler, pricing_calculator
def test_map_to_usage_entry_valid_data(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
data = {
"timestamp": "2024-01-01T12:00:00Z",
"message": {
"id": "msg_123",
"usage": {
"input_tokens": 100,
"output_tokens": 50,
"cache_creation_input_tokens": 10,
"cache_read_input_tokens": 5,
},
},
"model": "claude-3-haiku",
"request_id": "req_456",
"cost": 0.001,
}
with patch(
"claude_monitor.data.reader.TimestampProcessor"
) as mock_ts_processor:
mock_ts = Mock()
mock_ts.parse_timestamp.return_value = datetime(
2024, 1, 1, 12, 0, tzinfo=timezone.utc
)
mock_ts_processor.return_value = mock_ts
with patch(
"claude_monitor.data.reader.TokenExtractor"
) as mock_token_extractor:
mock_token_extractor.extract_tokens.return_value = {
"input_tokens": 100,
"output_tokens": 50,
"cache_creation_tokens": 10,
"cache_read_tokens": 5,
"total_tokens": 150,
}
with patch(
"claude_monitor.data.reader.DataConverter"
) as mock_data_converter:
mock_data_converter.extract_model_name.return_value = (
"claude-3-haiku"
)
pricing_calculator.calculate_cost_for_entry.return_value = 0.001
result = _map_to_usage_entry(
data, # type: ignore[arg-type] # Mock test data
CostMode.AUTO,
timezone_handler,
pricing_calculator,
)
assert result is not None
assert result.timestamp == datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc)
assert result.input_tokens == 100
assert result.output_tokens == 50
assert result.cache_creation_tokens == 10
assert result.cache_read_tokens == 5
assert result.cost_usd == 0.001
assert result.model == "claude-3-haiku"
assert result.message_id == "msg_123"
assert result.request_id == "req_456"
def test_map_to_usage_entry_no_timestamp(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
data = {"input_tokens": 100, "output_tokens": 50}
with patch(
"claude_monitor.core.data_processors.TimestampProcessor"
) as mock_ts_processor:
mock_ts = Mock()
mock_ts.parse_timestamp.return_value = None
mock_ts_processor.return_value = mock_ts
# Test with mock data dict - using dict literal for test data simplicity
result = _map_to_usage_entry(
data, # type: ignore[arg-type] # Mock test data
CostMode.AUTO,
timezone_handler,
pricing_calculator,
)
assert result is None
def test_map_to_usage_entry_no_tokens(
self, mock_components: tuple[Mock, Mock]
) -> None:
timezone_handler, pricing_calculator = mock_components
data = {"timestamp": "2024-01-01T12:00:00Z"}
with patch(
"claude_monitor.core.data_processors.TimestampProcessor"
) as mock_ts_processor:
mock_ts = Mock()
mock_ts.parse_timestamp.return_value = datetime(
2024, 1, 1, 12, 0, tzinfo=timezone.utc
)
mock_ts_processor.return_value = mock_ts
with patch(
"claude_monitor.core.data_processors.TokenExtractor"
) as mock_token_extractor:
mock_token_extractor.extract_tokens.return_value = {
"input_tokens": 0,
"output_tokens": 0,
"cache_creation_tokens": 0,
"cache_read_tokens": 0,
"total_tokens": 0,
}
# Test with mock data dict - using dict literal for test data simplicity
result = _map_to_usage_entry(
data, # type: ignore[arg-type] # Mock test data
CostMode.AUTO,
timezone_handler,
pricing_calculator,
)
assert result is None
def test_map_to_usage_entry_exception_handling(
self, mock_components: tuple[Mock, Mock]
) -> None:
"""Test _map_to_usage_entry with exception during processing."""
timezone_handler, pricing_calculator = mock_components
data = {"timestamp": "2024-01-01T12:00:00Z"}
with patch(
"claude_monitor.core.data_processors.TimestampProcessor",
side_effect=ValueError("Processing error"),
):
# Test with mock data dict - using dict literal for test data simplicity
result = _map_to_usage_entry(
data, # type: ignore[arg-type] # Mock test data
CostMode.AUTO,
timezone_handler,
pricing_calculator,
)
assert result is None
def test_map_to_usage_entry_minimal_data(
self, mock_components: tuple[Mock, Mock]
) -> None:
"""Test _map_to_usage_entry with minimal valid data."""
timezone_handler, pricing_calculator = mock_components
data = {
"timestamp": "2024-01-01T12:00:00Z",
"input_tokens": 100,
"output_tokens": 50,
}
with patch(
"claude_monitor.core.data_processors.TimestampProcessor"
) as mock_ts_processor:
mock_ts = Mock()
mock_ts.parse_timestamp.return_value = datetime(
2024, 1, 1, 12, 0, tzinfo=timezone.utc
)
mock_ts_processor.return_value = mock_ts
with patch(
"claude_monitor.core.data_processors.TokenExtractor"
) as mock_token_extractor:
mock_token_extractor.extract_tokens.return_value = {
"input_tokens": 100,
"output_tokens": 50,
"cache_creation_tokens": 0,
"cache_read_tokens": 0,
"total_tokens": 150,
}
with patch(
"claude_monitor.core.data_processors.DataConverter"
) as mock_data_converter:
mock_data_converter.extract_model_name.return_value = "unknown"
pricing_calculator.calculate_cost_for_entry.return_value = 0.0
# Test with mock data dict - using dict literal for test data simplicity
result = _map_to_usage_entry(
data, # type: ignore[arg-type] # Mock test data
CostMode.AUTO,
timezone_handler,
pricing_calculator,
)
assert result is not None
assert result.model == "unknown"
assert result.message_id == ""
assert result.request_id == "unknown"
class TestIntegration:
"""Integration tests for data reader functionality."""
def test_full_workflow_integration(self) -> None:
"""Test full workflow from file loading to entry creation."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Create test JSONL file
test_file = temp_path / "test.jsonl"
test_data = [
{
"timestamp": "2024-01-01T12:00:00Z",
"message": {
"id": "msg_1",
"usage": {"input_tokens": 100, "output_tokens": 50},
},
"model": "claude-3-haiku",
"request_id": "req_1",
},
{
"timestamp": "2024-01-01T13:00:00Z",
"message": {
"id": "msg_2",
"usage": {"input_tokens": 200, "output_tokens": 75},
},
"model": "claude-3-sonnet",
"request_id": "req_2",
},
]
with open(test_file, "w") as f:
f.writelines(json.dumps(item) + "\n" for item in test_data)
# Mock the data processors since they're external dependencies
with patch(
"claude_monitor.core.data_processors.TimestampProcessor"
) as mock_ts_processor:
mock_ts = Mock()
mock_ts.parse_timestamp.side_effect = [
datetime(2024, 1, 1, 12, 0, tzinfo=timezone.utc),
datetime(2024, 1, 1, 13, 0, tzinfo=timezone.utc),
]
mock_ts_processor.return_value = mock_ts
with patch(
"claude_monitor.core.data_processors.TokenExtractor"
) as mock_token_extractor:
mock_token_extractor.extract_tokens.side_effect = [
{
"input_tokens": 100,
"output_tokens": 50,
"cache_creation_tokens": 0,
"cache_read_tokens": 0,
},
{
"input_tokens": 200,
"output_tokens": 75,
"cache_creation_tokens": 0,
"cache_read_tokens": 0,
},
]
with patch(
"claude_monitor.core.data_processors.DataConverter"
) as mock_data_converter:
mock_data_converter.extract_model_name.side_effect = [
"claude-3-haiku",
"claude-3-sonnet",
]
with patch(
"claude_monitor.core.pricing.PricingCalculator"
) as mock_pricing_class:
mock_pricing = Mock()
mock_pricing.calculate_cost_for_entry.side_effect = [
0.001,
0.002,
]
mock_pricing_class.return_value = mock_pricing
# Execute the main function
entries, raw_data = load_usage_entries(
data_path=str(temp_path), include_raw=True
)
# Verify results
assert len(entries) == 2
# raw_data could be None, but we expect it to be a list in this test
assert raw_data is not None and len(raw_data) == 2
# First entry
assert entries[0].input_tokens == 100
assert entries[0].output_tokens == 50
assert entries[0].model == "claude-3-haiku"
assert entries[0].message_id == "msg_1"
# Second entry
assert entries[1].input_tokens == 200
assert entries[1].output_tokens == 75
assert entries[1].model == "claude-3-sonnet"
assert entries[1].message_id == "msg_2"