@@ -234,3 +234,57 @@ def handler(request):
234234 make_client (handler ).isochrone (block = "410390020001010" ,
235235 contours = [15 , 30 , 45 ])
236236 assert seen ["contours" ] == "15,30,45"
237+
238+
239+ # -- api key sourcing --------------------------------------------------------
240+
241+ def test_api_key_read_from_environment (monkeypatch ):
242+ monkeypatch .setenv ("CLOSECITY_KEY" , "ck_live_env" )
243+ seen = {}
244+
245+ def handler (request ):
246+ seen ["auth" ] = request .headers .get ("authorization" )
247+ return httpx .Response (200 , json = {"modes" : []})
248+
249+ Client (base_url = "https://api.close.city" , output = "raw" ,
250+ transport = httpx .MockTransport (handler )).modes ()
251+ assert seen ["auth" ] == "Bearer ck_live_env"
252+
253+
254+ def test_explicit_key_overrides_environment (monkeypatch ):
255+ monkeypatch .setenv ("CLOSECITY_KEY" , "ck_live_env" )
256+ seen = {}
257+
258+ def handler (request ):
259+ seen ["auth" ] = request .headers .get ("authorization" )
260+ return httpx .Response (200 , json = {"modes" : []})
261+
262+ Client ("ck_live_explicit" , base_url = "https://api.close.city" ,
263+ output = "raw" , transport = httpx .MockTransport (handler )).modes ()
264+ assert seen ["auth" ] == "Bearer ck_live_explicit"
265+
266+
267+ def test_missing_key_401_adds_actionable_hint (monkeypatch ):
268+ monkeypatch .delenv ("CLOSECITY_KEY" , raising = False )
269+
270+ def handler (request ):
271+ return problem (401 , "missing-key" , "Provide an API key." )
272+
273+ client = Client (base_url = "https://api.close.city" , output = "raw" ,
274+ transport = httpx .MockTransport (handler ))
275+ with pytest .raises (AuthenticationError ) as ei :
276+ client .block_summary ("410390020001010" )
277+ assert ei .value .hint is not None
278+ assert "CLOSECITY_KEY" in ei .value .hint
279+ assert "CLOSECITY_KEY" in str (ei .value )
280+
281+
282+ def test_invalid_key_401_has_no_missing_key_hint ():
283+ # A key IS set (make_client passes one), so the "you forgot your key" hint
284+ # must not fire on an invalid-key 401.
285+ def handler (request ):
286+ return problem (401 , "invalid-key" , "Unknown or revoked API key." )
287+
288+ with pytest .raises (AuthenticationError ) as ei :
289+ make_client (handler ).block_summary ("410390020001010" )
290+ assert ei .value .hint is None
0 commit comments