-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_app.py
More file actions
798 lines (675 loc) · 25.7 KB
/
test_app.py
File metadata and controls
798 lines (675 loc) · 25.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
import asyncio
from unittest.mock import MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import set_tracer_provider
from slm_server.app import DETAIL_SEM_TIMEOUT, app, get_llm, get_settings
from slm_server.config import Settings
# Create a mock Llama instance
mock_llama = MagicMock()
# Set up OpenTelemetry for tests
tracer_provider = TracerProvider()
memory_exporter = InMemorySpanExporter()
span_processor = SimpleSpanProcessor(memory_exporter)
tracer_provider.add_span_processor(span_processor)
set_tracer_provider(tracer_provider)
# Override the get_llm dependency with the mock
def override_get_llm():
return mock_llama
app.dependency_overrides[get_llm] = override_get_llm
# Use TestClient with lifespan context to ensure metrics endpoint is created
client = TestClient(app)
@pytest.fixture(autouse=True)
def reset_mock():
"""Reset the mock before each test."""
mock_llama.reset_mock()
mock_llama.create_chat_completion.side_effect = None # Clear any side effects
mock_llama.create_embedding.side_effect = None # Clear any side effects for embedding
# Patch the tracer in utils.py to use our test tracer
local_tracer = tracer_provider.get_tracer(__name__)
with patch('slm_server.utils.tracer', local_tracer):
yield
def test_chat_completion_non_streaming():
"""Tests the non-streaming chat completion endpoint."""
mock_llama.create_chat_completion.return_value = {
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello there!",
},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10},
}
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hello"}], "stream": False},
)
assert response.status_code == 200
assert response.json()["choices"][0]["message"]["content"] == "Hello there!"
mock_llama.create_chat_completion.assert_called_once()
def test_chat_completion_streaming():
"""Tests the streaming chat completion endpoint."""
mock_chunks = [
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"role": "assistant", "content": "Hello"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": " there!"},
"finish_reason": "stop",
}
],
},
]
mock_llama.create_chat_completion.return_value = iter(mock_chunks)
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hello"}], "stream": True},
)
assert response.status_code == 200
# Check that the response is a streaming response
assert "text/event-stream" in response.headers["content-type"]
# Collect the streaming content
content = response.text
assert "Hello" in content
assert "there!" in content
assert "data: [DONE]" in content
mock_llama.create_chat_completion.assert_called_once()
def test_server_busy_exception():
"""Tests the 503 Server Busy exception."""
# Simulate a timeout when acquiring the semaphore
with patch("asyncio.wait_for", side_effect=TimeoutError):
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hello"}], "stream": False},
)
assert response.status_code == 408
assert response.json()["detail"] == DETAIL_SEM_TIMEOUT
def test_generic_exception():
"""Tests the 500 Internal Server Error for unexpected exceptions."""
mock_llama.create_chat_completion.side_effect = Exception("Something went wrong")
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hello"}], "stream": False},
)
assert response.status_code == 500
assert "Something went wrong" in response.json()["detail"]
def test_streaming_stops_on_client_disconnect():
"""Tests that streaming handler stops gracefully when client disconnects."""
# Create a normal mock generator that would complete successfully
mock_chunks = [
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"choices": [{
"index": 0,
"delta": {"content": "Hello"},
"finish_reason": None,
}],
},
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"choices": [{
"index": 0,
"delta": {"content": " there"},
"finish_reason": None,
}],
},
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"choices": [{
"index": 0,
"delta": {"content": "!"},
"finish_reason": "stop",
}],
}
]
mock_llama.create_chat_completion.return_value = iter(mock_chunks)
cancellation_triggered = False
async def mock_run_llm_streaming_with_cancellation(llm, req):
"""Mock that yields some chunks then gets cancelled by client disconnect."""
nonlocal cancellation_triggered
from slm_server.utils.spans import slm_span, set_atrribute_response_stream
import json
with slm_span(req, is_streaming=True) as span:
try:
# Simulate asyncio.to_thread call
completion_stream = await asyncio.to_thread(
llm.create_chat_completion,
**req.model_dump(),
)
# Yield first chunk successfully
chunk = next(completion_stream)
set_atrribute_response_stream(span, chunk)
yield f"data: {json.dumps(chunk)}\n\n"
# Simulate client disconnect during streaming
raise asyncio.CancelledError("Client disconnected")
except asyncio.CancelledError:
cancellation_triggered = True
# Re-raise to let the span context manager handle it
raise
with patch('slm_server.app.run_llm_streaming', mock_run_llm_streaming_with_cancellation):
# Test that the cancellation handling works without requiring actual response content
# (since TestClient may not consume the stream when CancelledError is raised)
try:
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Hello"}], "stream": True},
)
# If we get here, the exception was handled gracefully
except Exception as e:
# Any unhandled exception means cancellation wasn't properly handled
pytest.fail(f"Cancellation not handled gracefully: {e}")
# Verify that our cancellation logic was triggered
assert cancellation_triggered, "CancelledError should have been raised and caught"
# Span is empty for some reason, but we can still check cancellation.
#
# Verify that spans were properly marked as cancelled (ERROR status with cancellation description)
#
# spans = memory_exporter.get_finished_spans()
# breakpoint()
# cancelled_spans = [s for s in spans if s.status.status_code.name == "ERROR" and "client disconnected" in s.status.description]
# assert len(cancelled_spans) > 0, "At least one span should be marked as cancelled"
def test_health_endpoint():
"""Tests the health endpoint."""
response = client.get("/health")
assert response.status_code == 200
assert response.json() == "ok"
def test_metrics_endpoint_integration():
"""Tests that /metrics endpoint integrates both OpenTelemetry and prometheus-fastapi-instrumentator metrics."""
# Make a request to generate metrics
health_response = client.get("/health")
assert health_response.status_code == 200
# Check metrics endpoint
metrics_response = client.get("/metrics")
assert metrics_response.status_code == 200
content = metrics_response.text
# Verify prometheus-fastapi-instrumentator custom metrics are present
assert "process_cpu_usage_percent" in content
assert "process_memory_usage_bytes" in content
# Verify standard Python metrics are present
assert "python_gc_objects_collected_total" in content
assert "python_info" in content
assert "process_virtual_memory_bytes" in content
# NOTE: SLM-specific metrics (slm_completion_duration_seconds, slm_tokens_total,
# etc.) are only registered when tracing is fully configured with endpoint and
# credentials. In the test environment tracing is not configured, so these
# metrics are not expected here. They are tested via test_trace.py.
def test_streaming_call_with_tracing_integration():
"""Integration test for streaming call with complete tracing flow."""
from unittest.mock import patch
# Mock chunks with realistic content
mock_chunks = [
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"role": "assistant", "content": "Hello"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": " there!"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-123",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": " How are you?"},
"finish_reason": "stop",
}
],
},
]
mock_llama.create_chat_completion.return_value = iter(mock_chunks)
# Make streaming request
response = client.post(
"/api/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "Hello world! This is a test message."}],
"stream": True,
"max_tokens": 100,
"temperature": 0.8
},
)
assert response.status_code == 200
assert "text/event-stream" in response.headers["content-type"]
# Verify streaming content
content = response.text
assert "Hello" in content
assert "there!" in content
assert "How are you?" in content
assert "data: [DONE]" in content
# Verify the LLM was called with correct parameters
mock_llama.create_chat_completion.assert_called_once()
call_args = mock_llama.create_chat_completion.call_args
assert call_args[1]["max_tokens"] == 100
assert call_args[1]["temperature"] == 0.8
assert call_args[1]["stream"] is True
assert len(call_args[1]["messages"]) == 1
assert call_args[1]["messages"][0]["content"] == "Hello world! This is a test message."
def test_non_streaming_call_with_tracing_integration():
"""Integration test for non-streaming call with complete tracing flow."""
from unittest.mock import patch
# Mock complete response with usage metrics
mock_llama.create_chat_completion.return_value = {
"id": "chatcmpl-456",
"object": "chat.completion",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! I'm doing well, thank you for asking. How can I help you today?",
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 20,
"total_tokens": 35
},
}
# Make non-streaming request
response = client.post(
"/api/v1/chat/completions",
json={
"messages": [
{"role": "user", "content": "Hello, how are you?"},
{"role": "assistant", "content": "I'm doing well!"},
{"role": "user", "content": "Great! Can you help me with something?"}
],
"stream": False,
"max_tokens": 150,
"temperature": 0.3
},
)
assert response.status_code == 200
# Verify response structure
response_data = response.json()
assert response_data["object"] == "chat.completion"
assert response_data["choices"][0]["message"]["content"] == "Hello! I'm doing well, thank you for asking. How can I help you today?"
assert response_data["usage"]["prompt_tokens"] == 15
assert response_data["usage"]["completion_tokens"] == 20
assert response_data["usage"]["total_tokens"] == 35
# Verify the LLM was called with correct parameters
mock_llama.create_chat_completion.assert_called_once()
call_args = mock_llama.create_chat_completion.call_args
assert call_args[1]["max_tokens"] == 150
assert call_args[1]["temperature"] == 0.3
assert call_args[1]["stream"] is False
assert len(call_args[1]["messages"]) == 3
# Verify message content
messages = call_args[1]["messages"]
assert messages[0]["content"] == "Hello, how are you?"
assert messages[1]["content"] == "I'm doing well!"
assert messages[2]["content"] == "Great! Can you help me with something?"
def test_streaming_call_with_empty_chunks():
"""Test streaming call handling empty chunks correctly."""
# Mock chunks including empty ones
mock_chunks = [
{
"id": "chatcmpl-789",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": "Start"},
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-789",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": ""}, # Empty chunk
"finish_reason": None,
}
],
},
{
"id": "chatcmpl-789",
"object": "chat.completion.chunk",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"delta": {"content": " End"},
"finish_reason": "stop",
}
],
},
]
mock_llama.create_chat_completion.return_value = iter(mock_chunks)
response = client.post(
"/api/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "Test empty chunks"}],
"stream": True
},
)
assert response.status_code == 200
# Verify content handling
content = response.text
assert "Start" in content
assert " End" in content
assert "data: [DONE]" in content
# Should handle empty chunks gracefully without errors
mock_llama.create_chat_completion.assert_called_once()
def test_embeddings_endpoint_string_input():
"""Tests the embeddings endpoint with string input."""
mock_llama.create_embedding.return_value = {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.1, -0.2, 0.3, -0.4, 0.5],
"index": 0
}
],
"model": "test-model",
"usage": {
"prompt_tokens": 5,
"total_tokens": 5
}
}
response = client.post(
"/api/v1/embeddings",
json={"input": "Hello world", "model": "test-model"}
)
assert response.status_code == 200
response_data = response.json()
assert response_data["object"] == "list"
assert len(response_data["data"]) == 1
assert response_data["data"][0]["object"] == "embedding"
assert response_data["data"][0]["embedding"] == [0.1, -0.2, 0.3, -0.4, 0.5]
assert response_data["data"][0]["index"] == 0
assert response_data["model"] == "test-model"
assert response_data["usage"]["prompt_tokens"] == 5
assert response_data["usage"]["total_tokens"] == 5
# Verify the LLM was called correctly
mock_llama.create_embedding.assert_called_once_with(
input="Hello world",
model="test-model"
)
def test_embeddings_endpoint_list_input():
"""Tests the embeddings endpoint with list input."""
mock_llama.create_embedding.return_value = {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.1, 0.2, 0.3],
"index": 0
},
{
"object": "embedding",
"embedding": [0.4, 0.5, 0.6],
"index": 1
}
],
"model": "test-model",
"usage": {
"prompt_tokens": 10,
"total_tokens": 10
}
}
response = client.post(
"/api/v1/embeddings",
json={"input": ["First text", "Second text"], "model": "test-model"}
)
assert response.status_code == 200
response_data = response.json()
assert response_data["object"] == "list"
assert len(response_data["data"]) == 2
assert response_data["data"][0]["embedding"] == [0.1, 0.2, 0.3]
assert response_data["data"][1]["embedding"] == [0.4, 0.5, 0.6]
assert response_data["usage"]["prompt_tokens"] == 10
# Verify the LLM was called correctly
mock_llama.create_embedding.assert_called_once_with(
input=["First text", "Second text"],
model="test-model"
)
def test_embeddings_endpoint_default_model():
"""Tests the embeddings endpoint with default model."""
mock_llama.create_embedding.return_value = {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.1, 0.2],
"index": 0
}
],
"model": "Qwen3-0.6B-GGUF",
"usage": {
"prompt_tokens": 3,
"total_tokens": 3
}
}
response = client.post(
"/api/v1/embeddings",
json={"input": "Test"}
)
assert response.status_code == 200
response_data = response.json()
assert response_data["model"] == "Qwen3-0.6B-GGUF"
# Verify default model was used
mock_llama.create_embedding.assert_called_once_with(
input="Test",
model=None # Default model is None
)
def test_embeddings_endpoint_error():
"""Tests the embeddings endpoint error handling."""
mock_llama.create_embedding.side_effect = Exception("Embedding failed")
response = client.post(
"/api/v1/embeddings",
json={"input": "Test", "model": "test-model"}
)
assert response.status_code == 500
assert "Embedding failed" in response.json()["detail"]
def test_embeddings_endpoint_empty_input():
"""Tests the embeddings endpoint with empty input."""
mock_llama.create_embedding.return_value = {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.0, 0.0],
"index": 0
}
],
"model": "test-model",
"usage": {
"prompt_tokens": 0,
"total_tokens": 0
}
}
response = client.post(
"/api/v1/embeddings",
json={"input": "", "model": "test-model"}
)
assert response.status_code == 200
response_data = response.json()
assert len(response_data["data"]) == 1
assert response_data["usage"]["prompt_tokens"] == 0
# Verify empty string was passed through
mock_llama.create_embedding.assert_called_once_with(
input="",
model="test-model"
)
def test_embeddings_endpoint_with_tracing_integration():
"""Integration test for embeddings endpoint with complete tracing flow."""
mock_llama.create_embedding.return_value = {
"object": "list",
"data": [
{
"object": "embedding",
"embedding": [0.1, -0.2, 0.3, -0.4, 0.5, 0.6, -0.7, 0.8],
"index": 0
}
],
"model": "test-model",
"usage": {
"prompt_tokens": 8,
"total_tokens": 8
}
}
response = client.post(
"/api/v1/embeddings",
json={
"input": "This is a test sentence for creating embeddings.",
"model": "test-model"
}
)
assert response.status_code == 200
response_data = response.json()
# Verify response structure
assert response_data["object"] == "list"
assert len(response_data["data"]) == 1
assert len(response_data["data"][0]["embedding"]) == 8
assert response_data["usage"]["prompt_tokens"] == 8
assert response_data["usage"]["total_tokens"] == 8
# Verify the LLM was called with correct parameters
mock_llama.create_embedding.assert_called_once()
call_args = mock_llama.create_embedding.call_args
assert call_args[1]["input"] == "This is a test sentence for creating embeddings."
assert call_args[1]["model"] == "test-model"
def test_request_validation_and_defaults():
"""Test request validation and default parameter handling."""
# Test minimal request
mock_llama.create_chat_completion.return_value = {
"id": "chatcmpl-minimal",
"object": "chat.completion",
"created": 1234567890,
"model": "test-model",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Response"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10},
}
response = client.post(
"/api/v1/chat/completions",
json={"messages": [{"role": "user", "content": "Test"}]},
)
assert response.status_code == 200
# Verify defaults were applied
call_args = mock_llama.create_chat_completion.call_args
assert call_args[1]["max_tokens"] is None # Default value
assert call_args[1]["temperature"] == 0.2 # Default value
assert call_args[1]["stream"] is False # Default value
def test_list_models_structure():
"""GET /api/v1/models returns OpenAI-compatible list with one model."""
response = client.get("/api/v1/models")
assert response.status_code == 200
data = response.json()
assert data["object"] == "list"
assert isinstance(data["data"], list)
assert len(data["data"]) == 1
model = data["data"][0]
assert model["object"] == "model"
assert "id" in model and isinstance(model["id"], str)
assert "created" in model and isinstance(model["created"], int)
assert model["owned_by"] == "second-state"
def test_list_models_with_overridden_settings():
"""GET /api/v1/models uses model_path and model_owner from settings."""
settings = Settings(
model_path="/tmp/SomeModel.gguf",
model_owner="custom-org",
)
def override_settings():
return settings
app.dependency_overrides[get_settings] = override_settings
try:
response = client.get("/api/v1/models")
assert response.status_code == 200
data = response.json()
assert data["object"] == "list"
assert len(data["data"]) == 1
model = data["data"][0]
assert model["id"] == "SomeModel"
assert model["object"] == "model"
assert model["owned_by"] == "custom-org"
assert model["created"] == 0 # file does not exist
finally:
app.dependency_overrides.pop(get_settings, None)
def test_list_models_created_from_existing_file(tmp_path):
"""GET /api/v1/models returns file mtime as created when model file exists."""
model_file = tmp_path / "RealModel.gguf"
model_file.write_bytes(b"\x00")
settings = Settings(model_path=str(model_file))
def override_settings():
return settings
app.dependency_overrides[get_settings] = override_settings
try:
response = client.get("/api/v1/models")
assert response.status_code == 200
model = response.json()["data"][0]
assert model["id"] == "RealModel"
assert model["created"] > 0
assert model["created"] == int(model_file.stat().st_mtime)
finally:
app.dependency_overrides.pop(get_settings, None)