1+ import unittest
2+ from unittest .mock import MagicMock , patch
3+
4+ from mcpm .router .transport import RouterSseTransport
5+
6+
7+ class TestApiKeyDisabled (unittest .TestCase ):
8+ """Test that API key validation is disabled when api_key is set to None."""
9+
10+ def test_api_key_disabled (self ):
11+ """Test that API key validation is disabled when api_key is set to None."""
12+ # Create a transport with api_key=None
13+ transport = RouterSseTransport ("/messages/" , api_key = None )
14+
15+ # Mock the scope
16+ scope = MagicMock ()
17+
18+ # Test that _validate_api_key returns True regardless of the api_key parameter
19+ self .assertTrue (transport ._validate_api_key (scope , api_key = None ))
20+ self .assertTrue (transport ._validate_api_key (scope , api_key = "some-key" ))
21+ self .assertTrue (transport ._validate_api_key (scope , api_key = "invalid-key" ))
22+
23+ def test_api_key_enabled (self ):
24+ """Test that API key validation works when api_key is set."""
25+ # Create a transport with a specific api_key
26+ transport = RouterSseTransport ("/messages/" , api_key = "test-key" )
27+
28+ # Mock the scope
29+ scope = MagicMock ()
30+
31+ # Test that _validate_api_key returns True only for the matching key
32+ self .assertTrue (transport ._validate_api_key (scope , api_key = "test-key" ))
33+ self .assertFalse (transport ._validate_api_key (scope , api_key = "wrong-key" ))
34+
35+ # When using the default validation logic, we need to mock the ConfigManager
36+ with patch ("mcpm.router.transport.ConfigManager" ) as mock_config_manager :
37+ # Set up the mock to make the default validation logic fail
38+ mock_instance = mock_config_manager .return_value
39+ mock_instance .read_share_config .return_value = {"url" : "http://example.com" , "api_key" : "share-key" }
40+ mock_instance .get_router_config .return_value = {"host" : "localhost" }
41+
42+ # Test with a key that doesn't match the transport's key
43+ self .assertFalse (transport ._validate_api_key (scope , api_key = "wrong-key" ))
44+
45+
46+ if __name__ == "__main__" :
47+ unittest .main ()
0 commit comments