@@ -71,6 +71,48 @@ def test_with_non_blocking_refresh():
7171 assert c ._use_non_blocking_refresh
7272
7373
74+ def test_with_headers ():
75+ credentials = CredentialsImpl ()
76+ request = mock .Mock ()
77+
78+ # 1. Add a new custom header
79+ creds_with_header = credentials .with_headers ({"X-Custom-Header" : "value1" })
80+ headers = {}
81+ creds_with_header .before_request (request , "http://example.com" , "GET" , headers )
82+ assert headers ["X-Custom-Header" ] == "value1"
83+ assert "authorization" in headers # Ensure base apply logic ran
84+ assert creds_with_header is not credentials
85+ assert not hasattr (credentials , "_custom_headers" ) or not credentials ._custom_headers
86+
87+ # 2. Update an existing custom header
88+ creds_updated = creds_with_header .with_headers ({"X-Custom-Header" : "value2" })
89+ headers = {}
90+ creds_updated .before_request (request , "http://example.com" , "GET" , headers )
91+ assert headers ["X-Custom-Header" ] == "value2"
92+
93+ # 3. Chaining with_headers calls
94+ creds_chained = credentials .with_headers ({"X-Header-1" : "v1" }).with_headers (
95+ {"X-Header-2" : "v2" }
96+ )
97+ headers = {}
98+ creds_chained .before_request (request , "http://example.com" , "GET" , headers )
99+ assert headers ["X-Header-1" ] == "v1"
100+ assert headers ["X-Header-2" ] == "v2"
101+
102+ # 4. Ensure protected headers cannot be set
103+ with pytest .raises (ValueError ):
104+ credentials .with_headers ({"Authorization" : "Bearer token" })
105+ with pytest .raises (ValueError ):
106+ credentials .with_headers ({"X-Goog-User-Project" : "test" })
107+ with pytest .raises (ValueError ):
108+ credentials .with_headers ({"authorization" : "Bearer token" }) # Case-insensitive
109+
110+ # 5. Check original credentials are not modified
111+ headers = {}
112+ credentials .before_request (request , "http://example.com" , "GET" , headers )
113+ assert "X-Custom-Header" not in headers
114+
115+
74116def test_expired_and_valid ():
75117 credentials = CredentialsImpl ()
76118 credentials .token = "token"
0 commit comments