-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathRocketRideClient_test.py
More file actions
2535 lines (2037 loc) · 98.7 KB
/
Copy pathRocketRideClient_test.py
File metadata and controls
2535 lines (2037 loc) · 98.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
# MIT License
#
# Copyright (c) 2026 Aparavi Software AG
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Integration Tests for RocketRideClient.
Comprehensive integration test suite for the RocketRide Python client, providing
test coverage for all major functionality including connections, pipelines,
data operations, chat operations, event handling, and error scenarios.
This is a pytest-based test suite that mirrors the TypeScript Jest integration
tests to ensure feature parity between client implementations.
Test Coverage:
- Server connection establishment and authentication
- Pipeline configuration and lifecycle management
- Data sending and processing operations
- File upload operations with progress tracking
- AI chat operations with streaming responses
- Real-time event handling and subscriptions
- Error handling and recovery scenarios
- End-to-end workflows with multiple operations
- Concurrent operation handling
Test Configuration:
Tests use environment variables for configuration:
- ROCKETRIDE_URI: Server URI (defaults to http://localhost:5565)
- ROCKETRIDE_APIKEY: Authentication key (defaults to 'MYAPIKEY')
- Various LLM API keys for chat tests (ROCKETRIDE_OPENAI_KEY, etc.)
Running Tests:
pytest tests/RocketRideClient_test.py -v # Verbose output
pytest tests/RocketRideClient_test.py -k test_name # Run specific test
pytest tests/RocketRideClient_test.py --log-cli-level=DEBUG # With debug logs
Note:
These integration tests require a running RocketRide server. Ensure the
server is running and accessible at the configured URI before running tests.
"""
import pytest
import asyncio
import os
import json
import random
import string
import tempfile
import time
from pathlib import Path
from typing import Dict, Any
from unittest.mock import AsyncMock
# Load .env from project root before any imports that need env vars
from dotenv import load_dotenv
PROJECT_ROOT = Path(__file__).parent.parent.parent.parent
load_dotenv(PROJECT_ROOT / '.env')
# Skip chat tests when no LLM API key is available
# fmt: off
HAS_LLM_KEY = bool(
os.environ.get('ROCKETRIDE_OPENAI_KEY')
or os.environ.get('ROCKETRIDE_ANTHROPIC_KEY')
or os.environ.get('ROCKETRIDE_GEMINI_KEY')
or os.environ.get('ROCKETRIDE_OLLAMA_HOST')
)
# fmt: on
requires_llm = pytest.mark.skipif(
not HAS_LLM_KEY,
reason='Skipped: no LLM API key set (need ROCKETRIDE_OPENAI_KEY, ROCKETRIDE_ANTHROPIC_KEY, ROCKETRIDE_GEMINI_KEY, or ROCKETRIDE_OLLAMA_HOST)',
)
# Import from rocketride
from rocketride import RocketRideClient, TASK_STATE, Question
from rocketride.mixins.connection import ConnectionMixin
# Import pipelines - using absolute imports since they're in the same directory
from echo_pipeline import get_echo_pipeline
from chat_pipeline import get_chat_pipeline
# Define type aliases for the types that may not be exported directly
UPLOAD_RESULT = Dict[str, Any]
PIPELINE_RESULT = Dict[str, Any]
EVENT_STATUS_UPDATE = Dict[str, Any]
EVENT_TASK = Dict[str, Any]
DAPMessage = Dict[str, Any]
# Test configuration
TEST_CONFIG = {
'uri': os.getenv('ROCKETRIDE_URI', 'http://localhost:5565'),
'auth': os.getenv('ROCKETRIDE_APIKEY', 'MYAPIKEY'),
'timeout': 30.0, # 30 second timeout for integration tests
}
async def ensure_clean_pipeline(client: RocketRideClient, token: str) -> None:
"""Clean up pipeline if it exists, ignoring errors."""
try:
await client.terminate(token)
except Exception:
# Ignore errors - pipeline might not be running
pass
class TestServerConnection:
"""Test basic server connection functionality."""
@pytest.mark.asyncio
async def test_should_connect_to_live_server(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
assert client.is_connected() is True
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_disconnect_from_server(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
assert client.is_connected() is True
await client.disconnect()
assert client.is_connected() is False
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_ping_server_successfully(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
await client.ping() # Should not raise an exception
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_connection_with_context_manager(self):
# This test may need to be adapted based on your client's actual context manager support
try:
async with RocketRideClient.with_connection(TEST_CONFIG) as connected_client:
assert connected_client.is_connected() is True
await connected_client.ping()
except AttributeError:
# If with_connection doesn't exist, test manual connection
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
assert client.is_connected() is True
await client.ping()
finally:
if client.is_connected():
await client.disconnect()
class TestServicesOperations:
"""Test service definition retrieval (get_services, get_service)."""
@pytest.mark.asyncio
async def test_should_get_all_services(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
result = await client.get_services()
assert isinstance(result, dict)
# Engine returns { "services": {...}, "version": ... }
assert 'services' in result
assert isinstance(result['services'], dict)
# May have version from engine
if 'version' in result:
assert isinstance(result['version'], (int, str))
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_get_single_service(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
all_services = await client.get_services()
services_dict = all_services.get('services', all_services)
if not services_dict:
pytest.skip('No services returned by server')
# Pick first available service name
service_name = next(iter(services_dict))
single = await client.get_service(service_name)
assert single is not None
assert isinstance(single, dict)
# Single service definition typically has title, protocol, schema, etc.
assert 'title' in single or 'protocol' in single or 'prefix' in single
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_raise_for_unknown_service(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
with pytest.raises(RuntimeError) as exc_info:
await client.get_service('nonexistent_service_xyz')
assert 'nonexistent_service_xyz' in str(exc_info.value) or 'not found' in str(exc_info.value).lower()
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_raise_when_service_name_empty(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
with pytest.raises(ValueError) as exc_info:
await client.get_service('')
assert 'required' in str(exc_info.value).lower()
finally:
if client.is_connected():
await client.disconnect()
class TestPipelineOperations:
"""Test pipeline lifecycle operations."""
PIPELINE_TOKEN = 'PY-PIPELINE-OPS'
@pytest.mark.asyncio
async def test_should_start_a_pipeline(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.PIPELINE_TOKEN)
assert 'token' in result
assert isinstance(result['token'], str)
assert len(result['token']) > 0
await client.terminate(result['token'])
finally:
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_get_pipeline_status(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.PIPELINE_TOKEN)
status = await client.get_task_status(result['token'])
assert 'state' in status
assert status['state'] in [state.value for state in TASK_STATE]
await client.terminate(result['token'])
finally:
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_terminate_a_pipeline(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
try:
await client.connect()
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.PIPELINE_TOKEN)
# Should not raise an exception
await client.terminate(result['token'])
finally:
await ensure_clean_pipeline(client, self.PIPELINE_TOKEN)
if client.is_connected():
await client.disconnect()
class TestDataOperations:
"""Test data sending and processing operations."""
DATA_TOKEN = 'PY-DATA-OPS'
@pytest.mark.asyncio
async def test_should_send_text_data_no_mime_type(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
test_data = 'Hello from integration test!'
result = await client.send(pipeline_token, test_data)
assert result is not None
assert isinstance(result, dict)
# Validate basic response structure
assert 'name' in result
assert isinstance(result['name'], str)
assert len(result['name']) == 36 # UUID format
assert 'path' in result
assert isinstance(result['path'], str)
assert result['path'] == '' # Should be empty for direct sends
assert 'objectId' in result
assert isinstance(result['objectId'], str)
assert len(result['objectId']) == 36 # UUID format
# Without MIME type, should not have processed content
assert 'result_types' not in result or result['result_types'] is None
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_send_text_data_after_use_with_filepath(self):
"""Regression for docs flow: use(filepath=...) followed by send(...)."""
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
token = f'{self.DATA_TOKEN}-filepath'
try:
await client.connect()
await ensure_clean_pipeline(client, token)
# Mirror docs-style usage where pipeline config is loaded from disk.
pipeline_config = get_echo_pipeline()
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', encoding='utf-8', delete=False) as temp_file:
json.dump(pipeline_config, temp_file)
temp_path = temp_file.name
try:
result = await client.use(filepath=temp_path, token=token)
pipeline_token = result['token']
send_result = await client.send(pipeline_token, 'Hello, pipeline!', objinfo={'name': 'input.txt'}, mimetype='text/plain')
assert send_result is not None
assert isinstance(send_result, dict)
assert 'result_types' in send_result
assert isinstance(send_result['result_types'], dict)
assert send_result['result_types'].get('text') == 'text'
assert 'text' in send_result
assert isinstance(send_result['text'], list)
assert any('Hello, pipeline!' in chunk for chunk in send_result['text'])
finally:
if os.path.exists(temp_path):
os.unlink(temp_path)
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
else:
await ensure_clean_pipeline(client, token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_send_text_data_with_mime_type(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
test_data = 'Hello from integration test!'
result = await client.send(pipeline_token, test_data, {}, 'text/plain')
assert result is not None
assert isinstance(result, dict)
# Validate basic response structure
assert 'name' in result
assert isinstance(result['name'], str)
assert len(result['name']) == 36
assert 'path' in result
assert isinstance(result['path'], str)
assert result['path'] == ''
assert 'objectId' in result
assert isinstance(result['objectId'], str)
assert len(result['objectId']) == 36
# With MIME type, should have processed content
assert 'result_types' in result
assert isinstance(result['result_types'], dict)
assert result['result_types']['text'] == 'text'
# Validate the actual data field referenced by result_types
assert 'text' in result
assert isinstance(result['text'], list)
assert len(result['text']) > 0
assert 'Hello from integration test!' in result['text'][0]
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_send_binary_data(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
binary_data = bytes([72, 101, 108, 108, 111]) # "Hello" in bytes
result = await client.send(pipeline_token, binary_data)
assert result is not None
assert isinstance(result, dict)
# Validate basic response structure
assert 'name' in result
assert isinstance(result['name'], str)
assert len(result['name']) == 36
assert 'path' in result
assert isinstance(result['path'], str)
assert result['path'] == ''
assert 'objectId' in result
assert isinstance(result['objectId'], str)
assert len(result['objectId']) == 36
# Binary data without MIME type should not have processed content
assert 'result_types' not in result or result['result_types'] is None
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_use_data_pipe_for_streaming(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
pipe = await client.pipe(pipeline_token, {'name': 'test-stream.txt'}, 'text/plain')
await pipe.open()
chunks = ['Hello ', 'from ', 'streaming ', 'test!']
for chunk in chunks:
await pipe.write(chunk.encode())
result = await pipe.close()
assert result is not None
assert isinstance(result, dict)
# Should use the provided name instead of UUID for streaming
assert result['name'] == 'test-stream.txt'
assert 'path' in result
assert isinstance(result['path'], str)
assert result['path'] == ''
assert 'objectId' in result
assert isinstance(result['objectId'], str)
assert len(result['objectId']) == 36
# Streaming with MIME type should have processed content
assert 'result_types' in result
assert result['result_types']['text'] == 'text'
assert 'text' in result
assert isinstance(result['text'], list)
assert len(result['text']) > 0
assert result['text'][0] == '\n\n'.join(chunks) + '\n\n'
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_file_uploads(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
name = 'test.txt'
test_content = 'Test file content for upload'
# Create file file
with open(name, 'w') as f:
# Create the file
f.write(test_content)
f.close()
# Upload and process file
try:
upload_results = await client.send_files([(name, {'name': name}, 'text/plain')], pipeline_token)
finally:
os.unlink(name) # Ensure temp file is deleted
assert upload_results is not None
assert isinstance(upload_results, list)
assert len(upload_results) == 1
upload_result = upload_results[0]
# Validate UPLOAD_RESULT structure
assert upload_result['action'] == 'complete'
assert upload_result['filepath'] == name
assert upload_result['bytes_sent'] == len(test_content)
assert upload_result['file_size'] == len(test_content)
assert isinstance(upload_result['upload_time'], (int, float))
assert upload_result['upload_time'] >= 0
assert 'error' not in upload_result or upload_result['error'] is None
# Validate processing result
assert 'result' in upload_result
processing_result = upload_result['result']
# Should use original filename
assert processing_result['name'] == name
assert processing_result['path'] == ''
assert len(processing_result['objectId']) == 36
# File uploads should have processed content
assert 'result_types' in processing_result
assert processing_result['result_types']['text'] == 'text'
assert 'text' in processing_result
assert isinstance(processing_result['text'], list)
assert test_content + '\n\n' in processing_result['text']
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_different_result_types_field_mappings(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
test_data = 'Multi-field result type test'
result = await client.send(pipeline_token, test_data, {}, 'text/plain')
assert result is not None
if result.get('result_types'):
# Check each field exists and has the right type
for field_name, field_type in result['result_types'].items():
assert field_name in result
# For text type fields, should be string arrays
if field_type == 'text':
assert isinstance(result[field_name], list)
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_various_mime_types_and_result_structures(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
pipeline_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.DATA_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.DATA_TOKEN)
pipeline_token = result['token']
test_cases = [{'data': 'Plain text content', 'mime_type': 'text/plain', 'description': 'plain text'}, {'data': json.dumps({'message': 'Hello', 'value': 42}), 'mime_type': 'application/json', 'description': 'JSON data'}]
for test_case in test_cases:
result = await client.send(pipeline_token, test_case['data'], {}, test_case['mime_type'])
assert result is not None
print(f'Testing {test_case["description"]}: {json.dumps(result, indent=2)}')
# All results should have basic fields
assert 'name' in result
assert 'objectId' in result
if result.get('result_types'):
# Check result_types structure
assert isinstance(result['result_types'], dict)
# Verify fields referenced in result_types actually exist
for field_name, field_type in result['result_types'].items():
assert field_name in result
print(f" Field '{field_name}' (type: {field_type}): {result[field_name]}")
# Basic type checking
if field_type == 'text':
assert isinstance(result[field_name], list)
finally:
if pipeline_token:
await ensure_clean_pipeline(client, pipeline_token)
if client.is_connected():
await client.disconnect()
@requires_llm
class TestChatOperations:
"""Test chat functionality."""
CHAT_TOKEN = 'PY-CHAT-OPS'
@pytest.mark.asyncio
async def test_should_send_simple_chat_question(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
chat_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.CHAT_TOKEN)
result = await client.use(pipeline=get_chat_pipeline(), token=self.CHAT_TOKEN)
chat_token = result['token']
question = Question()
question.addQuestion('What is 2 + 2?')
response = await client.chat(
token=chat_token,
question=question,
)
assert response is not None
assert isinstance(response, dict)
# Validate basic response structure
assert 'name' in response
assert isinstance(response['name'], str)
assert 'path' in response
assert 'objectId' in response
assert len(response['objectId']) == 36
# Chat should have processed content with answers
assert 'result_types' in response
assert response['result_types']['answers'] == 'answers'
# Validate the answers field
assert 'answers' in response
assert isinstance(response['answers'], list)
assert len(response['answers']) > 0
# Check that we got a meaningful answer
answer = response['answers'][0]
assert isinstance(answer, str)
assert len(answer) > 0
finally:
if chat_token:
await ensure_clean_pipeline(client, chat_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_json_response_questions(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
chat_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.CHAT_TOKEN)
result = await client.use(pipeline=get_chat_pipeline(), token=self.CHAT_TOKEN)
chat_token = result['token']
question = Question(expectJson=True)
question.addQuestion('Cite the first paragraph of the constitution of the United States')
question.addExample('greeting request', {'text': 'Hello, world!'})
response = await client.chat(
token=chat_token,
question=question,
)
assert response is not None
assert isinstance(response, dict)
# Validate basic response structure
assert 'name' in response
assert 'path' in response
assert 'objectId' in response
# Should have answers field
assert 'result_types' in response
assert response['result_types']['answers'] == 'answers'
assert 'answers' in response
assert isinstance(response['answers'], list)
assert len(response['answers']) > 0
# Validate answer content
answer = response['answers'][0]
assert isinstance(answer, dict)
assert 'text' in answer
assert len(answer['text']) > 0
assert 'We the People' in answer['text']
finally:
if chat_token:
await ensure_clean_pipeline(client, chat_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_questions_with_instructions(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
chat_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.CHAT_TOKEN)
result = await client.use(pipeline=get_chat_pipeline(), token=self.CHAT_TOKEN)
chat_token = result['token']
question = Question()
question.addQuestion('Tell me about machine learning')
question.addInstruction('Format', 'Keep the response under 100 words')
question.addInstruction('Tone', 'Use simple, beginner-friendly language and talk like yoda')
response = await client.chat(
token=chat_token,
question=question,
)
assert response is not None
assert isinstance(response, dict)
# Validate basic response structure
assert 'name' in response
assert 'path' in response
assert 'objectId' in response
# Should have answers field
assert 'result_types' in response
assert response['result_types']['answers'] == 'answers'
assert 'answers' in response
assert isinstance(response['answers'], list)
assert len(response['answers']) > 0
# Check that we got a meaningful answer
answer = response['answers'][0]
assert isinstance(answer, str)
assert len(answer) > 0
finally:
if chat_token:
await ensure_clean_pipeline(client, chat_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_handle_questions_with_context(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
chat_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.CHAT_TOKEN)
result = await client.use(pipeline=get_chat_pipeline(), token=self.CHAT_TOKEN)
chat_token = result['token']
question = Question()
question.addContext('This is a test environment')
question.addContext('The user is learning about the RocketRide API')
question.addQuestion('Explain what just happened in this interaction')
response = await client.chat(
token=chat_token,
question=question,
)
assert response is not None
assert isinstance(response, dict)
# Validate basic response structure
assert 'name' in response
assert 'path' in response
assert 'objectId' in response
# Should have answers field
assert 'result_types' in response
assert response['result_types']['answers'] == 'answers'
assert 'answers' in response
assert isinstance(response['answers'], list)
assert len(response['answers']) > 0
# Check that we got a response
answer = response['answers'][0]
assert isinstance(answer, str)
assert len(answer) > 0
finally:
if chat_token:
await ensure_clean_pipeline(client, chat_token)
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_validate_chat_response_structure_matches_pipeline_result(self):
client = RocketRideClient(auth=TEST_CONFIG['auth'], uri=TEST_CONFIG['uri'])
chat_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.CHAT_TOKEN)
result = await client.use(pipeline=get_chat_pipeline(), token=self.CHAT_TOKEN)
chat_token = result['token']
question = Question()
question.addQuestion('What is the weather like today?')
response = await client.chat(
token=chat_token,
question=question,
)
# Verify it's a standard PIPELINE_RESULT
assert 'name' in response
assert 'path' in response
assert 'objectId' in response
# Check result_types specifically for chat responses
if response.get('result_types'):
for field_name, field_type in response['result_types'].items():
assert field_name in response
# For answers type fields, should be string arrays
if field_type == 'answers':
assert isinstance(response[field_name], list)
if len(response[field_name]) > 0:
assert isinstance(response[field_name][0], str)
finally:
if chat_token:
await ensure_clean_pipeline(client, chat_token)
if client.is_connected():
await client.disconnect()
class TestConnectionEvents:
"""Test connection event callbacks."""
@pytest.mark.asyncio
async def test_should_call_connected_disconnected_callbacks(self):
connected_spy = AsyncMock()
disconnected_spy = AsyncMock()
client = RocketRideClient(
auth=TEST_CONFIG['auth'],
uri=TEST_CONFIG['uri'],
on_connected=connected_spy,
on_disconnected=disconnected_spy,
)
try:
assert client.is_connected() is False
await client.connect()
assert client.is_connected() is True
connected_spy.assert_called_once()
assert isinstance(connected_spy.call_args[0][0], str)
disconnected_spy.assert_not_called()
await client.disconnect()
assert client.is_connected() is False
disconnected_spy.assert_called_once()
call_args = disconnected_spy.call_args[0]
assert isinstance(call_args[0], str) # reason
assert call_args[1] is False # has_error
finally:
if client.is_connected():
await client.disconnect()
@pytest.mark.asyncio
async def test_should_call_disconnected_with_error_flag_on_connection_failure(self):
connected_spy = AsyncMock()
disconnected_spy = AsyncMock()
# Use an invalid URI that will definitely fail to connect
client = RocketRideClient(
auth='INVALID_KEY',
uri='http://localhost:59999', # Non-existent server
on_connected=connected_spy,
on_disconnected=disconnected_spy,
)
with pytest.raises(Exception):
await client.connect()
connected_spy.assert_not_called()
if disconnected_spy.call_count > 0:
call_args = disconnected_spy.call_args[0]
assert call_args[1] is True # has_error
# This is Part 2 - paste this after Part 1
class TestEventHandling:
"""Test event subscription and handling."""
EVENT_TOKEN = 'PY-EVENT-OPS'
@pytest.mark.asyncio
async def test_should_subscribe_to_events_and_receive_them(self):
received_events = []
async def event_handler(event):
received_events.append(event)
client = RocketRideClient(
auth=TEST_CONFIG['auth'],
uri=TEST_CONFIG['uri'],
on_event=event_handler,
)
event_token = None
try:
await client.connect()
await ensure_clean_pipeline(client, self.EVENT_TOKEN)
result = await client.use(pipeline=get_echo_pipeline(), token=self.EVENT_TOKEN)
event_token = result['token']
await client.set_events(event_token, ['summary'])
await client.send(event_token, 'Test data for events')
# Wait with timeout for events
timeout = 10.0
start = time.time()
while len(received_events) == 0 and (time.time() - start) < timeout:
await asyncio.sleep(0.25)
# Verify we got events
assert len(received_events) >= 0
# If we got events, verify their structure
if len(received_events) > 0:
event = received_events[0]
assert 'event' in event