This repository was archived by the owner on Jun 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathtest_v1_processing.py
More file actions
531 lines (511 loc) · 19.6 KB
/
test_v1_processing.py
File metadata and controls
531 lines (511 loc) · 19.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
import datetime
import json
from unittest.mock import AsyncMock, patch
import pytest
from codegate.api import v1_models
from codegate.api.v1_processing import (
_get_partial_question_answer,
_group_partial_messages,
_is_system_prompt,
parse_output,
parse_request,
remove_duplicate_alerts,
)
from codegate.db.models import GetPromptWithOutputsRow
@pytest.mark.asyncio
@pytest.mark.parametrize(
"message, expected_bool",
[
("Hello, how can I help you?", False),
(
"Given the following... please reply with a short summary that is 4-12 words in length",
True,
),
],
)
async def test_is_system_prompt(message, expected_bool):
result = await _is_system_prompt(message)
assert result == expected_bool
@pytest.mark.asyncio
@pytest.mark.parametrize(
"request_dict, expected_str_list",
[
(
{"messages": [{"role": "user", "content": "Hello, how can I help you?"}]},
["Hello, how can I help you?"],
),
(
{
"messages": [ # Request with system prompt
{
"role": "user",
"content": "Given the following... please reply with a short summary",
}
]
},
None,
),
(
{
"messages": [ # Request with multiple messages
{"role": "user", "content": "Hello, how can I help you?"},
{"role": "user", "content": "Hello, latest"},
]
},
["Hello, how can I help you?", "Hello, latest"],
),
(
{
"messages": [ # Request with content list
{
"role": "user",
"content": [{"type": "text", "text": "Hello, how can I help you?"}],
},
]
},
["Hello, how can I help you?"],
),
({"prompt": "Hello, how can I help you?"}, ["Hello, how can I help you?"]),
],
)
async def test_parse_request(request_dict, expected_str_list):
request_str = json.dumps(request_dict)
result, _ = await parse_request(request_str)
assert result == expected_str_list
@pytest.mark.asyncio
@pytest.mark.parametrize(
"output_dict, expected_str",
[
(
[ # Stream output with multiple chunks
{
"id": "chatcmpl-AaQw9O1O2u360mhba5UbMoPwFgqEl",
"created": 1733246717,
"model": "gpt-4o-mini",
"object": "chat.completion.chunk",
"system_fingerprint": "fp_0705bf87c0",
"choices": [{"index": 0, "delta": {"content": "Hello", "role": "assistant"}}],
},
{
"id": "chatcmpl-AaQw9O1O2u360mhba5UbMoPwFgqEl",
"created": 1733246717,
"model": "gpt-4o-mini",
"object": "chat.completion.chunk",
"system_fingerprint": "fp_0705bf87c0",
"choices": [{"index": 0, "delta": {"content": " world"}}],
},
{
"id": "chatcmpl-AaQw9O1O2u360mhba5UbMoPwFgqEl",
"created": 1733246717,
"model": "gpt-4o-mini",
"object": "chat.completion.chunk",
"system_fingerprint": "fp_0705bf87c0",
"choices": [{"finish_reason": "stop", "index": 0, "delta": {}}],
},
],
"Hello world",
),
(
{
"id": "chatcmpl-AaQw9O1O2u360mhba5UbMoPwFgqEa",
"created": 1733246717,
"model": "gpt-4o-mini",
"object": "chat.completion.chunk",
"system_fingerprint": "fp_0705bf87c0",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {"content": "User seeks", "role": "assistant"},
}
],
},
"User seeks",
),
],
)
async def test_parse_output(output_dict, expected_str):
request_str = json.dumps(output_dict)
output_message = await parse_output(request_str)
assert output_message == expected_str
timestamp_now = datetime.datetime.now(datetime.timezone.utc)
@pytest.mark.asyncio
@pytest.mark.parametrize("request_msg_list", [["Hello"], None])
@pytest.mark.parametrize("output_msg_str", ["Hello, how can I help you?", None])
@pytest.mark.parametrize(
"row",
[
GetPromptWithOutputsRow(
id="1",
timestamp=timestamp_now,
provider="openai",
request="foo",
type="chat",
output_id="2",
output="bar",
output_timestamp=timestamp_now,
input_tokens=None,
output_tokens=None,
input_cost=None,
output_cost=None,
)
],
)
async def test_get_question_answer(request_msg_list, output_msg_str, row):
with patch(
"codegate.api.v1_processing.parse_request", new_callable=AsyncMock
) as mock_parse_request:
with patch(
"codegate.api.v1_processing.parse_output", new_callable=AsyncMock
) as mock_parse_output:
# Set return values for the mocks
mock_parse_request.return_value = request_msg_list, "openai"
mock_parse_output.return_value = output_msg_str
result = await _get_partial_question_answer(row)
mock_parse_request.assert_called_once()
mock_parse_output.assert_called_once()
if request_msg_list is None:
assert result is None
else:
assert result.partial_questions.messages == request_msg_list
if output_msg_str is not None:
assert result.answer.message == output_msg_str
assert result.partial_questions.provider == "openai"
assert result.partial_questions.type == "chat"
@pytest.mark.parametrize(
"pq_list,expected_group_ids",
[
# 1) No subsets: all items stand alone
(
[
v1_models.PartialQuestions(
messages=["A"],
timestamp=datetime.datetime(2023, 1, 1, 0, 0, 0),
message_id="pq1",
provider="providerA",
type="chat",
),
v1_models.PartialQuestions(
messages=["B"],
timestamp=datetime.datetime(2023, 1, 1, 0, 0, 1),
message_id="pq2",
provider="providerA",
type="chat",
),
],
[["pq1"], ["pq2"]],
),
# 2) Single subset: one is a subset of the other
# - "Hello" is a subset of "Hello, how are you?"
(
[
v1_models.PartialQuestions(
messages=["Hello"],
timestamp=datetime.datetime(2022, 1, 1, 0, 0, 0),
message_id="pq1",
provider="providerA",
type="chat",
),
v1_models.PartialQuestions(
messages=["Hello", "How are you?"],
timestamp=datetime.datetime(2022, 1, 1, 0, 0, 10),
message_id="pq2",
provider="providerA",
type="chat",
),
],
[["pq1", "pq2"]],
),
# 3) Multiple identical subsets:
# We have 3 partial questions with messages=["Hello"],
# plus a superset with messages=["Hello", "Bye"].
# Only the single subset that is closest in timestamp to the superset is grouped with the
# superset.
(
[
v1_models.PartialQuestions(
messages=["Hello"],
timestamp=datetime.datetime(2023, 1, 1, 10, 0, 0),
message_id="pq1",
provider="providerA",
type="chat",
),
v1_models.PartialQuestions(
messages=["Hello"],
timestamp=datetime.datetime(2023, 1, 1, 11, 0, 0),
message_id="pq2",
provider="providerA",
type="chat",
),
v1_models.PartialQuestions(
messages=["Hello"],
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 0),
message_id="pq3",
provider="providerA",
type="chat",
),
v1_models.PartialQuestions(
messages=["Hello", "Bye"],
timestamp=datetime.datetime(2023, 1, 1, 11, 0, 5),
message_id="pq4",
provider="providerA",
type="chat",
),
],
# pq4 is the superset => subsets are pq1, pq2, pq3.
# The closest subset to pq4(11:00:05) is pq2(11:00:00).
# So group = [pq2, pq4].
# The other two remain alone in their own group.
# The final sorted order is by earliest timestamp in each group:
# group with pq1 => [pq1], earliest 10:00:00
# group with pq2, pq4 => earliest 11:00:00
# group with pq3 => earliest 12:00:00
[["pq1"], ["pq2", "pq4"], ["pq3"]],
),
# 4) Mixed: multiple subsets, multiple supersets, verifying group logic
(
[
# Superset
v1_models.PartialQuestions(
messages=["hi", "welcome", "bye"],
timestamp=datetime.datetime(2023, 5, 1, 9, 0, 0),
message_id="pqS1",
provider="providerB",
type="chat",
),
# Subsets for pqS1
v1_models.PartialQuestions(
messages=["hi", "welcome"],
timestamp=datetime.datetime(2023, 5, 1, 9, 0, 5),
message_id="pqA1",
provider="providerB",
type="chat",
),
v1_models.PartialQuestions(
messages=["hi", "bye"],
timestamp=datetime.datetime(2023, 5, 1, 9, 0, 10),
message_id="pqA2",
provider="providerB",
type="chat",
),
v1_models.PartialQuestions(
messages=["hi", "bye"],
timestamp=datetime.datetime(2023, 5, 1, 9, 0, 12),
message_id="pqA3",
provider="providerB",
type="chat",
),
# Another superset
v1_models.PartialQuestions(
messages=["apple", "banana", "cherry"],
timestamp=datetime.datetime(2023, 5, 2, 10, 0, 0),
message_id="pqS2",
provider="providerB",
type="chat",
),
# Subsets for pqS2
v1_models.PartialQuestions(
messages=["banana"],
timestamp=datetime.datetime(2023, 5, 2, 10, 0, 1),
message_id="pqB1",
provider="providerB",
type="chat",
),
v1_models.PartialQuestions(
messages=["apple", "banana"],
timestamp=datetime.datetime(2023, 5, 2, 10, 0, 3),
message_id="pqB2",
provider="providerB",
type="chat",
),
# Another item alone, not a subset nor superset
v1_models.PartialQuestions(
messages=["xyz"],
timestamp=datetime.datetime(2023, 5, 3, 8, 0, 0),
message_id="pqC1",
provider="providerB",
type="chat",
),
# Different provider => should remain separate
v1_models.PartialQuestions(
messages=["hi", "welcome"],
timestamp=datetime.datetime(2023, 5, 1, 9, 0, 10),
message_id="pqProvDiff",
provider="providerX",
type="chat",
),
],
# Expected:
# For pqS1 (["hi","welcome","bye"]) => subsets are pqA1(["hi","welcome"]),
# pqA2 & pqA3 (["hi","bye"])
# Among pqA2 and pqA3, we pick the one closest in time to 09:00:00 =>
# that is pqA2(09:00:10) vs pqA3(09:00:12).
# The absolute difference:
# pqA2 => 10 seconds
# pqA3 => 12 seconds
# So we pick pqA2. Group => [pqS1, pqA1, pqA2]
#
# For pqS2 (["apple","banana","cherry"]) => subsets are pqB1(["banana"]),
# pqB2(["apple","banana"])
# Among them, we group them all (because they have distinct messages).
# So => [pqS2, pqB1, pqB2]
#
# pqC1 stands alone => ["pqC1"]
# pqProvDiff stands alone => ["pqProvDiff"] because provider is different
#
# Then we sort by earliest timestamp in each group:
# group with pqS1 => earliest is 09:00:00
# group with pqProvDiff => earliest is 09:00:10
# group with pqS2 => earliest is 10:00:00
# group with pqC1 => earliest is 08:00:00 on 5/3 => actually this is the last date,
# so let's see:
# 2023-05-01 is earlier than 2023-05-02, which is earlier than 2023-05-03.
# Actually, 2023-05-03 is later. So "pqC1" group is last in chronological order.
#
# Correct chronological order of earliest timestamps:
# 1) [pqS1, pqA1, pqA2] => earliest 2023-05-01 09:00:00
# 2) [pqProvDiff] => earliest 2023-05-01 09:00:10
# 3) [pqS2, pqB1, pqB2] => earliest 2023-05-02 10:00:00
# 4) [pqC1] => earliest 2023-05-03 08:00:00
[["pqS1", "pqA1", "pqA2"], ["pqProvDiff"], ["pqS2", "pqB1", "pqB2"], ["pqC1"]],
),
],
)
def test_group_partial_messages(pq_list, expected_group_ids):
"""
Verify that _group_partial_messages produces the correct grouping
(by message_id) in the correct order.
"""
# Execute
grouped = _group_partial_messages(pq_list)
# Convert from list[list[v1_models.PartialQuestions]] -> list[list[str]]
# so we can compare with expected_group_ids easily.
grouped_ids = [[pq.message_id for pq in group] for group in grouped]
is_matched = False
print(grouped_ids)
for group_id in grouped_ids:
for expected_group in expected_group_ids:
if set(group_id) == set(expected_group):
is_matched = True
break
assert is_matched
@pytest.mark.asyncio
@pytest.mark.parametrize(
"alerts,expected_count,expected_ids",
[
# Test Case 1: Non-secret alerts pass through unchanged
(
[
v1_models.Alert(
id="1",
prompt_id="p1",
code_snippet=None,
trigger_string="test1",
trigger_type="other-alert",
trigger_category="info",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 0),
),
v1_models.Alert(
id="2",
prompt_id="p2",
code_snippet=None,
trigger_string="test2",
trigger_type="other-alert",
trigger_category="info",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 1),
),
],
2, # Expected count
["1", "2"], # Expected IDs preserved
),
# Test Case 2: Duplicate secrets within 5 seconds - keep newer only
(
[
v1_models.Alert(
id="1",
prompt_id="p1",
code_snippet=None,
trigger_string="secret1 Context xyz",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 0),
),
v1_models.Alert(
id="2",
prompt_id="p2",
code_snippet=None,
trigger_string="secret1 Context abc",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 3),
),
],
1, # Expected count
["2"], # Only newer alert ID
),
# Test Case 3: Similar secrets beyond 5 seconds - keep both
(
[
v1_models.Alert(
id="1",
prompt_id="p1",
code_snippet=None,
trigger_string="secret1 Context xyz",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 0),
),
v1_models.Alert(
id="2",
prompt_id="p2",
code_snippet=None,
trigger_string="secret1 Context abc",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 6),
),
],
2, # Expected count
["1", "2"], # Both alerts preserved
),
# Test Case 4: Mix of secret and non-secret alerts
(
[
v1_models.Alert(
id="1",
prompt_id="p1",
code_snippet=None,
trigger_string="secret1 Context xyz",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 0),
),
v1_models.Alert(
id="2",
prompt_id="p2",
code_snippet=None,
trigger_string="non-secret alert",
trigger_type="other-alert",
trigger_category="info",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 1),
),
v1_models.Alert(
id="3",
prompt_id="p3",
code_snippet=None,
trigger_string="secret1 Context abc",
trigger_type="codegate-secrets",
trigger_category="critical",
timestamp=datetime.datetime(2023, 1, 1, 12, 0, 3),
),
],
2, # Expected count
["2", "3"], # Non-secret alert and newest secret alert
),
],
)
async def test_remove_duplicate_alerts(alerts, expected_count, expected_ids):
result = await remove_duplicate_alerts(alerts)
assert len(result) == expected_count
result_ids = [alert.id for alert in result]
assert sorted(result_ids) == sorted(expected_ids)