File size: 29,204 Bytes
bf9e111 | 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 | # -*- coding: utf-8 -*-
"""
Common fixtures and utilities for testing Kiro Gateway.
Provides test isolation from external services and global state.
All tests MUST be completely isolated from the network.
"""
import asyncio
import json
import pytest
import time
from typing import AsyncGenerator, Dict, Any, List
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from datetime import datetime, timezone
import httpx
from fastapi.testclient import TestClient
# =============================================================================
# Event Loop Fixtures
# =============================================================================
@pytest.fixture(scope="session")
def event_loop():
"""
Creates an event loop for the entire test session.
Required for proper async fixture operation.
"""
print("Creating event loop for test session...")
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
print("Closing event loop...")
loop.close()
# =============================================================================
# Environment Fixtures
# =============================================================================
@pytest.fixture
def mock_env_vars(monkeypatch):
"""
Mocks environment variables for isolation from real credentials.
"""
print("Setting up mocked environment variables...")
monkeypatch.setenv("REFRESH_TOKEN", "test_refresh_token_abcdef")
monkeypatch.setenv("PROXY_API_KEY", "test_proxy_key_12345")
monkeypatch.setenv("PROFILE_ARN", "arn:aws:codewhisperer:us-east-1:123456789:profile/test")
monkeypatch.setenv("KIRO_REGION", "us-east-1")
return {
"REFRESH_TOKEN": "test_refresh_token_abcdef",
"PROXY_API_KEY": "test_proxy_key_12345",
"PROFILE_ARN": "arn:aws:codewhisperer:us-east-1:123456789:profile/test",
"KIRO_REGION": "us-east-1"
}
# =============================================================================
# Token and Authentication Fixtures
# =============================================================================
@pytest.fixture
def valid_kiro_token():
"""Returns a valid mock Kiro access token."""
return "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.test_kiro_access_token"
@pytest.fixture
def mock_kiro_token_response(valid_kiro_token):
"""
Factory for creating mock Kiro token refresh endpoint responses.
"""
def _create_response(expires_in: int = 3600, token: str = None):
return {
"accessToken": token or valid_kiro_token,
"refreshToken": "new_refresh_token_xyz",
"expiresIn": expires_in,
"profileArn": "arn:aws:codewhisperer:us-east-1:123456789:profile/test"
}
return _create_response
@pytest.fixture
def valid_proxy_api_key():
"""Returns a valid proxy API key (from config)."""
return "changeme_proxy_secret"
@pytest.fixture
def invalid_proxy_api_key():
"""Returns an invalid API key for negative tests."""
return "invalid_wrong_secret_key"
@pytest.fixture
def auth_headers(valid_proxy_api_key):
"""
Factory for creating valid and invalid Authorization headers.
"""
def _create_headers(api_key: str = None, invalid: bool = False):
if invalid:
return {"Authorization": "Bearer wrong_key_123"}
key = api_key or valid_proxy_api_key
return {"Authorization": f"Bearer {key}"}
return _create_headers
# =============================================================================
# Kiro Models Fixtures
# =============================================================================
@pytest.fixture
def mock_kiro_models_response():
"""
Mock successful response from Kiro API for ListAvailableModels.
"""
return {
"models": [
{
"modelId": "claude-sonnet-4.5",
"displayName": "Claude Sonnet 4.5",
"tokenLimits": {
"maxInputTokens": 200000,
"maxOutputTokens": 8192
}
},
{
"modelId": "claude-opus-4.5",
"displayName": "Claude Opus 4.5",
"tokenLimits": {
"maxInputTokens": 200000,
"maxOutputTokens": 8192
}
},
{
"modelId": "claude-haiku-4.5",
"displayName": "Claude Haiku 4.5",
"tokenLimits": {
"maxInputTokens": 200000,
"maxOutputTokens": 8192
}
}
]
}
# =============================================================================
# Kiro Streaming Response Fixtures
# =============================================================================
@pytest.fixture
def mock_kiro_streaming_chunks():
"""
Returns a list of mock SSE chunks from Kiro API for streaming response.
Covers: regular text, tool calls, usage.
"""
return [
# Chunk 1: Text start
b'{"content":"Hello"}',
# Chunk 2: Text continuation
b'{"content":" World!"}',
# Chunk 3: Tool call start
b'{"name":"get_weather","toolUseId":"call_abc123"}',
# Chunk 4: Tool call input
b'{"input":"{\\"location\\": \\"Moscow\\"}"}',
# Chunk 5: Tool call stop
b'{"stop":true}',
# Chunk 6: Usage
b'{"usage":1.5}',
# Chunk 7: Context usage
b'{"contextUsagePercentage":25.5}',
]
@pytest.fixture
def mock_kiro_simple_text_chunks():
"""
Mock simple text response from Kiro (without tool calls).
"""
return [
b'{"content":"This is a complete response."}',
b'{"usage":0.5}',
b'{"contextUsagePercentage":10.0}',
]
@pytest.fixture
def mock_kiro_stream_with_usage():
"""
Mock Kiro SSE response with usage information.
"""
return [
b'{"content":"Final text."}',
b'{"usage":1.3}',
b'{"contextUsagePercentage":50.0}',
]
# =============================================================================
# OpenAI Request Fixtures
# =============================================================================
@pytest.fixture
def sample_openai_chat_request():
"""
Factory for creating valid OpenAI chat completion requests.
"""
def _create_request(
model: str = "claude-sonnet-4-5",
messages: list = None,
stream: bool = False,
temperature: float = None,
max_tokens: int = None,
tools: list = None,
**kwargs
):
if messages is None:
messages = [{"role": "user", "content": "Hello, AI!"}]
request = {
"model": model,
"messages": messages,
"stream": stream
}
if temperature is not None:
request["temperature"] = temperature
if max_tokens is not None:
request["max_tokens"] = max_tokens
if tools is not None:
request["tools"] = tools
request.update(kwargs)
return request
return _create_request
@pytest.fixture
def sample_tool_definition():
"""
Sample tool definition for testing tool calling.
"""
return {
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}
}
# =============================================================================
# HTTP Client Fixtures
# =============================================================================
@pytest.fixture
async def mock_httpx_client():
"""
Creates a mocked httpx.AsyncClient for isolation from network requests.
"""
print("Creating mocked httpx.AsyncClient...")
mock_client = AsyncMock(spec=httpx.AsyncClient)
# Mock methods
mock_client.post = AsyncMock()
mock_client.get = AsyncMock()
mock_client.aclose = AsyncMock()
mock_client.build_request = Mock()
mock_client.send = AsyncMock()
mock_client.is_closed = False
return mock_client
@pytest.fixture
def mock_httpx_response():
"""
Factory for creating mocked httpx.Response objects.
"""
def _create_response(
status_code: int = 200,
json_data: Dict[str, Any] = None,
text: str = None,
stream_chunks: list = None
):
print(f"Creating mock httpx.Response (status={status_code})...")
mock_response = AsyncMock(spec=httpx.Response)
mock_response.status_code = status_code
if json_data is not None:
mock_response.json = Mock(return_value=json_data)
if text is not None:
mock_response.text = text
mock_response.content = text.encode()
if stream_chunks is not None:
# For streaming responses
async def mock_aiter_bytes():
for chunk in stream_chunks:
yield chunk
mock_response.aiter_bytes = mock_aiter_bytes
mock_response.raise_for_status = Mock()
mock_response.aclose = AsyncMock()
mock_response.aread = AsyncMock(return_value=b'{"error": "mocked error"}')
return mock_response
return _create_response
# =============================================================================
# Global Network Blocking
# =============================================================================
@pytest.fixture(scope="session", autouse=True)
def block_all_network_calls():
"""
CRITICAL FIXTURE: Globally blocks ALL network calls.
Ensures that NO test can make a real network request.
"""
# Create a mock that will be used for all AsyncClient instances
mock_async_client = AsyncMock(spec=httpx.AsyncClient)
async def network_call_error(*args, **kwargs):
raise RuntimeError(
"🚨 CRITICAL ERROR: Real network request attempt detected! "
"Test did not provide a mock for httpx.AsyncClient. "
"All HTTP calls must be explicitly mocked."
)
mock_async_client.post.side_effect = network_call_error
mock_async_client.get.side_effect = network_call_error
mock_async_client.send.side_effect = network_call_error
# Mock context manager
mock_async_client.__aenter__ = AsyncMock(return_value=mock_async_client)
mock_async_client.__aexit__ = AsyncMock()
mock_async_client.aclose = AsyncMock()
mock_async_client.is_closed = False
# Patch AsyncClient in modules where it's used
patchers = [
patch('kiro.auth.httpx.AsyncClient', return_value=mock_async_client),
patch('kiro.http_client.httpx.AsyncClient', return_value=mock_async_client),
patch('kiro.streaming_openai.httpx.AsyncClient', return_value=mock_async_client),
]
# Start patchers
for patcher in patchers:
patcher.start()
print("🛡️ GLOBAL NETWORK BLOCKING ACTIVATED")
yield
# Stop patchers
for patcher in patchers:
patcher.stop()
print("🛡️ GLOBAL NETWORK BLOCKING DEACTIVATED")
# =============================================================================
# Application Fixtures
# =============================================================================
@pytest.fixture
def clean_app():
"""
Returns a "clean" application instance for each test.
"""
print("Importing application for test...")
from main import app
# Reset all dependency overrides before test
app.dependency_overrides = {}
return app
@pytest.fixture
def test_client(clean_app):
"""
Creates a FastAPI TestClient for synchronous endpoint tests,
properly handling lifespan events.
"""
print("Creating TestClient with lifespan support...")
with TestClient(clean_app) as client:
yield client
print("Closing TestClient...")
@pytest.fixture
async def async_test_client(clean_app):
"""
Creates an asynchronous test client for async endpoints.
"""
print("Creating async test client...")
from httpx import AsyncClient, ASGITransport
transport = ASGITransport(app=clean_app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
print("Closing async test client...")
# =============================================================================
# KiroAuthManager Fixtures
# =============================================================================
@pytest.fixture
def mock_auth_manager():
"""
Creates a mocked KiroAuthManager for tests.
"""
from kiro.auth import KiroAuthManager
manager = KiroAuthManager(
refresh_token="test_refresh_token",
profile_arn="arn:aws:codewhisperer:us-east-1:123456789:profile/test",
region="us-east-1"
)
# Set valid token
manager._access_token = "test_access_token"
manager._expires_at = datetime.now(timezone.utc).replace(
year=2099 # Far in the future
)
return manager
@pytest.fixture
def expired_auth_manager():
"""
Creates a KiroAuthManager with an expired token.
"""
from kiro.auth import KiroAuthManager
manager = KiroAuthManager(
refresh_token="test_refresh_token",
profile_arn="arn:aws:codewhisperer:us-east-1:123456789:profile/test",
region="us-east-1"
)
# Set expired token
manager._access_token = "expired_token"
manager._expires_at = datetime.now(timezone.utc).replace(
year=2020 # In the past
)
return manager
# =============================================================================
# ModelInfoCache Fixtures
# =============================================================================
@pytest.fixture
def sample_models_data():
"""
Returns a list of models for testing ModelInfoCache.
"""
return [
{
"modelId": "claude-sonnet-4",
"displayName": "Claude Sonnet 4",
"tokenLimits": {
"maxInputTokens": 200000,
"maxOutputTokens": 8192
}
},
{
"modelId": "claude-opus-4.5",
"displayName": "Claude Opus 4.5",
"tokenLimits": {
"maxInputTokens": 200000,
"maxOutputTokens": 8192
}
},
{
"modelId": "claude-haiku-4.5",
"displayName": "Claude Haiku 4.5",
"tokenLimits": {
"maxInputTokens": 100000,
"maxOutputTokens": 4096
}
}
]
@pytest.fixture
def empty_model_cache():
"""
Creates an empty ModelInfoCache.
"""
from kiro.cache import ModelInfoCache
return ModelInfoCache()
@pytest.fixture
async def populated_model_cache(mock_kiro_models_response):
"""
Creates a ModelInfoCache with pre-populated data.
"""
from kiro.cache import ModelInfoCache
cache = ModelInfoCache()
await cache.update(mock_kiro_models_response["models"])
return cache
# =============================================================================
# Time Fixtures
# =============================================================================
@pytest.fixture
def mock_time():
"""
Mocks time.time() for predictable behavior in tests.
"""
with patch('time.time') as mock:
# Fixed point in time: 2024-01-01 12:00:00
mock.return_value = 1704110400.0
yield mock
@pytest.fixture
def mock_datetime():
"""
Mocks datetime.now() for predictable behavior.
"""
fixed_time = datetime(2024, 1, 1, 12, 0, 0, tzinfo=timezone.utc)
with patch('kiro.auth.datetime') as mock_dt:
mock_dt.now.return_value = fixed_time
mock_dt.fromisoformat = datetime.fromisoformat
mock_dt.fromtimestamp = datetime.fromtimestamp
yield mock_dt
# =============================================================================
# Temporary File Fixtures
# =============================================================================
@pytest.fixture
def temp_creds_file(tmp_path):
"""
Creates a temporary credentials file for tests (Kiro Desktop format).
"""
creds_file = tmp_path / "kiro-auth-token.json"
creds_data = {
"accessToken": "file_access_token",
"refreshToken": "file_refresh_token",
"expiresAt": "2099-01-01T00:00:00.000Z",
"profileArn": "arn:aws:codewhisperer:us-east-1:123456789:profile/test",
"region": "us-east-1"
}
creds_file.write_text(json.dumps(creds_data))
return str(creds_file)
@pytest.fixture
def temp_aws_sso_creds_file(tmp_path):
"""
Creates a temporary credentials file for tests (AWS SSO OIDC format).
Contains clientId and clientSecret, indicating AWS SSO OIDC authentication.
"""
creds_file = tmp_path / "aws-sso-cache.json"
creds_data = {
"accessToken": "aws_sso_access_token",
"refreshToken": "aws_sso_refresh_token",
"expiresAt": "2099-01-01T00:00:00.000Z",
"region": "us-east-1",
"clientId": "test_client_id_12345",
"clientSecret": "test_client_secret_67890"
}
creds_file.write_text(json.dumps(creds_data))
return str(creds_file)
@pytest.fixture
def temp_sqlite_db(tmp_path):
"""
Creates a temporary SQLite database for tests (kiro-cli format).
Contains auth_kv table with keys:
- 'codewhisperer:odic:token': JSON with access_token, refresh_token, expires_at, region
- 'codewhisperer:odic:device-registration': JSON with client_id, client_secret
"""
import sqlite3
db_file = tmp_path / "data.sqlite3"
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
# Create auth_kv table
cursor.execute("""
CREATE TABLE auth_kv (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Insert token data
token_data = {
"access_token": "sqlite_access_token",
"refresh_token": "sqlite_refresh_token",
"expires_at": "2099-01-01T00:00:00Z",
"region": "eu-west-1"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("codewhisperer:odic:token", json.dumps(token_data))
)
# Insert device registration data
registration_data = {
"client_id": "sqlite_client_id",
"client_secret": "sqlite_client_secret",
"region": "eu-west-1"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("codewhisperer:odic:device-registration", json.dumps(registration_data))
)
conn.commit()
conn.close()
return str(db_file)
@pytest.fixture
def temp_sqlite_db_token_only(tmp_path):
"""
Creates a SQLite database with token only (without device-registration).
Used for testing partial loading.
"""
import sqlite3
db_file = tmp_path / "data_token_only.sqlite3"
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE auth_kv (
key TEXT PRIMARY KEY,
value TEXT
)
""")
token_data = {
"access_token": "partial_access_token",
"refresh_token": "partial_refresh_token",
"region": "ap-southeast-1"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("codewhisperer:odic:token", json.dumps(token_data))
)
conn.commit()
conn.close()
return str(db_file)
@pytest.fixture
def temp_sqlite_db_invalid_json(tmp_path):
"""
Creates a SQLite database with invalid JSON in value.
Used for testing error handling.
"""
import sqlite3
db_file = tmp_path / "data_invalid.sqlite3"
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE auth_kv (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Insert invalid JSON
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("codewhisperer:odic:token", "not a valid json {{{")
)
conn.commit()
conn.close()
return str(db_file)
@pytest.fixture
def mock_aws_sso_oidc_token_response():
"""
Factory for creating mock AWS SSO OIDC token endpoint responses.
"""
def _create_response(
access_token: str = "new_aws_sso_access_token",
refresh_token: str = "new_aws_sso_refresh_token",
expires_in: int = 3600
):
return {
"accessToken": access_token,
"refreshToken": refresh_token,
"expiresIn": expires_in,
"tokenType": "Bearer"
}
return _create_response
@pytest.fixture
def temp_debug_dir(tmp_path):
"""
Creates a temporary directory for debug files.
"""
debug_dir = tmp_path / "debug_logs"
debug_dir.mkdir()
return debug_dir
# =============================================================================
# Parser Fixtures
# =============================================================================
@pytest.fixture
def aws_event_parser():
"""
Creates an AwsEventStreamParser instance for tests.
"""
from kiro.parsers import AwsEventStreamParser
return AwsEventStreamParser()
# =============================================================================
# Test Utilities
# =============================================================================
def create_kiro_content_chunk(content: str) -> bytes:
"""Utility for creating a Kiro SSE chunk with content."""
return f'{{"content":"{content}"}}'.encode()
def create_kiro_tool_start_chunk(name: str, tool_id: str) -> bytes:
"""Utility for creating a Kiro SSE chunk with tool call start."""
return f'{{"name":"{name}","toolUseId":"{tool_id}"}}'.encode()
def create_kiro_tool_input_chunk(input_json: str) -> bytes:
"""Utility for creating a Kiro SSE chunk with tool call input."""
escaped = input_json.replace('"', '\\"')
return f'{{"input":"{escaped}"}}'.encode()
def create_kiro_tool_stop_chunk() -> bytes:
"""Utility for creating a Kiro SSE chunk with tool call stop."""
return b'{"stop":true}'
def create_kiro_usage_chunk(usage: float) -> bytes:
"""Utility for creating a Kiro SSE chunk with usage."""
return f'{{"usage":{usage}}}'.encode()
def create_kiro_context_usage_chunk(percentage: float) -> bytes:
"""Utility for creating a Kiro SSE chunk with context usage."""
return f'{{"contextUsagePercentage":{percentage}}}'.encode()
# =============================================================================
# Social Login Fixtures (for new functionality)
# =============================================================================
@pytest.fixture
def temp_sqlite_db_social(tmp_path):
"""
Creates a temporary SQLite database with social login credentials.
Contains auth_kv table with key:
- 'kirocli:social:token': JSON with access_token, refresh_token, expires_at, provider
This simulates kiro-cli with Google/GitHub social login (no client_id/client_secret).
"""
import sqlite3
db_file = tmp_path / "data_social.sqlite3"
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
# Create auth_kv table
cursor.execute("""
CREATE TABLE auth_kv (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Insert social login token data
token_data = {
"access_token": "social_access_token",
"refresh_token": "social_refresh_token",
"expires_at": "2099-01-01T00:00:00Z",
"provider": "google",
"profile_arn": "arn:aws:codewhisperer:us-east-1:123456789:profile/social",
"region": "us-east-1"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("kirocli:social:token", json.dumps(token_data))
)
conn.commit()
conn.close()
return str(db_file)
@pytest.fixture
def temp_sqlite_db_all_keys(tmp_path):
"""
Creates a SQLite database with ALL three token keys.
Used for testing key priority:
1. kirocli:social:token (highest priority)
2. kirocli:odic:token
3. codewhisperer:odic:token (lowest priority)
"""
import sqlite3
db_file = tmp_path / "data_all_keys.sqlite3"
conn = sqlite3.connect(str(db_file))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE auth_kv (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Insert all three keys with different tokens
social_data = {
"access_token": "social_token",
"refresh_token": "social_refresh",
"expires_at": "2099-01-01T00:00:00Z",
"provider": "google"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("kirocli:social:token", json.dumps(social_data))
)
odic_data = {
"access_token": "odic_token",
"refresh_token": "odic_refresh",
"expires_at": "2099-01-01T00:00:00Z"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("kirocli:odic:token", json.dumps(odic_data))
)
legacy_data = {
"access_token": "legacy_token",
"refresh_token": "legacy_refresh",
"expires_at": "2099-01-01T00:00:00Z"
}
cursor.execute(
"INSERT INTO auth_kv (key, value) VALUES (?, ?)",
("codewhisperer:odic:token", json.dumps(legacy_data))
)
conn.commit()
conn.close()
return str(db_file)
# =============================================================================
# Enterprise Kiro IDE Fixtures (Issue #45)
# =============================================================================
@pytest.fixture
def temp_enterprise_ide_creds_file(tmp_path):
"""
Creates a temporary credentials file for Enterprise Kiro IDE.
Contains:
- clientIdHash: Hash used to locate device registration file
- refreshToken, accessToken, expiresAt, region
This simulates Enterprise Kiro IDE with IdC (AWS IAM Identity Center) login.
"""
creds_file = tmp_path / "kiro-auth-token.json"
creds_data = {
"accessToken": "enterprise_access_token",
"refreshToken": "enterprise_refresh_token",
"expiresAt": "2099-01-01T00:00:00.000Z",
"profileArn": "arn:aws:codewhisperer:us-east-1:123456789:profile/enterprise",
"region": "us-east-1",
"clientIdHash": "abc123def456"
}
creds_file.write_text(json.dumps(creds_data))
return str(creds_file)
@pytest.fixture
def temp_enterprise_device_registration(tmp_path):
"""
Creates a temporary device registration file for Enterprise Kiro IDE.
Located at: ~/.aws/sso/cache/{clientIdHash}.json
Contains: clientId, clientSecret
"""
# Create .aws/sso/cache directory structure
aws_dir = tmp_path / ".aws" / "sso" / "cache"
aws_dir.mkdir(parents=True, exist_ok=True)
# Create device registration file
device_reg_file = aws_dir / "abc123def456.json"
device_reg_data = {
"clientId": "enterprise_client_id_12345",
"clientSecret": "enterprise_client_secret_67890",
"region": "us-east-1"
}
device_reg_file.write_text(json.dumps(device_reg_data))
return str(device_reg_file)
@pytest.fixture
def temp_enterprise_ide_complete(tmp_path, monkeypatch):
"""
Creates a complete Enterprise IDE setup with both credentials and device registration.
Returns tuple: (creds_file_path, device_reg_file_path)
"""
# Mock Path.home() to return tmp_path
monkeypatch.setattr('pathlib.Path.home', lambda: tmp_path)
# Create credentials file
creds_file = tmp_path / "kiro-auth-token.json"
creds_data = {
"accessToken": "enterprise_access_token",
"refreshToken": "enterprise_refresh_token",
"expiresAt": "2099-01-01T00:00:00.000Z",
"profileArn": "arn:aws:codewhisperer:us-east-1:123456789:profile/enterprise",
"region": "us-east-1",
"clientIdHash": "abc123def456"
}
creds_file.write_text(json.dumps(creds_data))
# Create device registration file
aws_dir = tmp_path / ".aws" / "sso" / "cache"
aws_dir.mkdir(parents=True, exist_ok=True)
device_reg_file = aws_dir / "abc123def456.json"
device_reg_data = {
"clientId": "enterprise_client_id_12345",
"clientSecret": "enterprise_client_secret_67890",
"region": "us-east-1"
}
device_reg_file.write_text(json.dumps(device_reg_data))
return (str(creds_file), str(device_reg_file))
|