"""Tests for graphql_client module.""" import pytest import os from unittest.mock import patch from src.graphql_client import ( GraphQLClient, create_client, UpdateResult, BatchResult, UPDATE_DELIVERY_DATE_MUTATION, ) class TestUpdateResult: """Tests for UpdateResult dataclass.""" def test_successful_result(self): """Test successful update result.""" result = UpdateResult( pub_song_id=134224, success=True, response_data={ "data": {"updatePublishingCompositionsDeliveryDate": [{"id": "123"}]} }, ) assert result.pub_song_id == 134224 assert result.success is True assert result.error_message is None assert result.response_data is not None def test_failed_result(self): """Test failed update result.""" result = UpdateResult( pub_song_id=134224, success=False, error_message="GraphQL error: Invalid pub_song_id", ) assert result.pub_song_id == 134224 assert result.success is False assert result.error_message == "GraphQL error: Invalid pub_song_id" class TestBatchResult: """Tests for BatchResult dataclass.""" def test_batch_result_properties(self): """Test BatchResult calculated properties.""" results = [ UpdateResult(1, True), UpdateResult(2, True), UpdateResult(3, False, "Error"), ] batch = BatchResult(successful_updates=2, failed_updates=1, results=results) assert batch.total_updates == 3 assert batch.success_rate == 2 / 3 class TestGraphQLClient: """Tests for GraphQLClient class.""" def test_client_initialization(self): """Test GraphQL client initialization.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } with patch.dict( os.environ, {"QA_GRAPHQL_URL": "https://qa-example.com/graphql"} ): client = GraphQLClient("qa", user_config) assert client.environment == "qa" assert client.user_config == user_config assert client.base_url == "https://qa-example.com/graphql" def test_headers_with_user_config(self): """Test header generation with user configuration.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } with patch.dict( os.environ, {"QA_GRAPHQL_URL": "https://qa-example.com/graphql"} ): client = GraphQLClient("qa", user_config) headers = client._get_headers() assert headers["Orchard-Profile-Id"] == "479520" assert ( headers["Orchard-Identity-Id"] == "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7" ) assert headers["Content-Type"] == "application/json" def test_headers_with_env_fallback(self): """Test header generation with environment variable fallback.""" env_vars = { "QA_GRAPHQL_URL": "https://qa-example.com/graphql", "ORCHARD_PROFILE_ID": "479520", "ORCHARD_IDENTITY_ID": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } with patch.dict(os.environ, env_vars): client = GraphQLClient("qa") headers = client._get_headers() assert headers["Orchard-Profile-Id"] == "479520" assert ( headers["Orchard-Identity-Id"] == "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7" ) def test_get_environment_display_name(self): """Test environment display name.""" user_config = {"profile_id": "123", "identity_id": "abc"} with patch.dict( os.environ, {"QA_GRAPHQL_URL": "https://qa-example.com/graphql"} ): qa_client = GraphQLClient("qa", user_config) assert qa_client.get_environment_display_name() == "QA" with patch.dict( os.environ, {"PROD_GRAPHQL_URL": "https://prod-example.com/graphql"} ): prod_client = GraphQLClient("prod", user_config) assert prod_client.get_environment_display_name() == "PROD" def test_validate_configuration_success(self): """Test successful configuration validation.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } env_vars = { "QA_GRAPHQL_URL": "https://qa-example.com/graphql", "CHUNK_SIZE": "200", } with patch.dict(os.environ, env_vars): client = GraphQLClient("qa", user_config) errors = client.validate_configuration() assert len(errors) == 0 def test_validate_configuration_missing_user_config(self): """Test configuration validation with missing user config.""" user_config = {"profile_id": "479520"} # Missing identity_id env_vars = { "QA_GRAPHQL_URL": "https://qa-example.com/graphql", "CHUNK_SIZE": "200", } with patch.dict(os.environ, env_vars, clear=True): # Mock the _get_headers method to avoid the missing config error during init with patch.object(GraphQLClient, "_get_headers", return_value={}): client = GraphQLClient("qa", user_config) errors = client.validate_configuration() assert len(errors) > 0 assert any("identity_id" in error for error in errors) def test_validate_configuration_missing_env_vars(self): """Test configuration validation with missing environment variables.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } # Test missing URL by not creating the client, since it fails at init with patch.dict(os.environ, {}, clear=True): # Clear all env vars with pytest.raises(ValueError) as exc_info: GraphQLClient("qa", user_config) assert "GraphQL URL not configured" in str(exc_info.value) def test_update_delivery_date_method_exists(self): """Test that update_delivery_date method exists and has correct signature.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } with patch.dict( os.environ, {"QA_GRAPHQL_URL": "https://qa-example.com/graphql"} ): client = GraphQLClient("qa", user_config) # Test that the method exists and is async import inspect method = getattr(client, "update_delivery_date") assert callable(method) assert inspect.iscoroutinefunction(method) def test_update_delivery_dates_batch_method_exists(self): """Test that update_delivery_dates_batch method exists.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } with patch.dict( os.environ, {"QA_GRAPHQL_URL": "https://qa-example.com/graphql"} ): client = GraphQLClient("qa", user_config) # Test that the method exists and is an async generator import inspect method = getattr(client, "update_delivery_dates_batch") assert callable(method) assert inspect.ismethod(method) or inspect.isfunction(method) class TestCreateClient: """Tests for create_client factory function.""" def test_create_client_success(self): """Test successful client creation.""" user_config = { "profile_id": "479520", "identity_id": "7dc01da2-cda8-4a3f-ad40-f3308b4a37d7", } env_vars = { "QA_GRAPHQL_URL": "https://qa-example.com/graphql", "CHUNK_SIZE": "200", } with patch.dict(os.environ, env_vars): client = create_client("qa", user_config) assert isinstance(client, GraphQLClient) assert client.environment == "qa" def test_create_client_validation_error(self): """Test client creation with validation errors.""" user_config = {"profile_id": "479520"} # Missing identity_id with patch.dict(os.environ, {}, clear=True): with pytest.raises(ValueError) as exc_info: create_client("qa", user_config) # Could be URL error or configuration error error_msg = str(exc_info.value) assert ( "GraphQL URL not configured" in error_msg or "configuration errors" in error_msg ) class TestConstants: """Tests for module constants.""" def test_mutation_string(self): """Test that the GraphQL mutation string is properly defined.""" assert ( "updatePublishingCompositionsDeliveryDate" in UPDATE_DELIVERY_DATE_MUTATION ) assert "$pubSongId: Int!" in UPDATE_DELIVERY_DATE_MUTATION assert "$deliveryDate: String!" in UPDATE_DELIVERY_DATE_MUTATION