Skip to content

Commit ae796fc

Browse files
committed
black
1 parent 3f45fb2 commit ae796fc

File tree

4 files changed

+52
-77
lines changed

4 files changed

+52
-77
lines changed

sdk/identity/azure-identity/azure/identity/_credentials/azure_cli.py

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,7 @@ def get_token(
115115
receive an access token.
116116
"""
117117
if claims and claims.strip():
118-
raise CredentialUnavailableError(
119-
f"Fail to get token, please run az login --claims-challenge {claims}"
120-
)
118+
raise CredentialUnavailableError(f"Fail to get token, please run az login --claims-challenge {claims}")
121119

122120
options: TokenRequestOptions = {}
123121
if tenant_id:
@@ -127,9 +125,7 @@ def get_token(
127125
return AccessToken(token_info.token, token_info.expires_on)
128126

129127
@log_get_token
130-
def get_token_info(
131-
self, *scopes: str, options: Optional[TokenRequestOptions] = None
132-
) -> AccessTokenInfo:
128+
def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
133129
"""Request an access token for `scopes`.
134130
135131
This is an alternative to `get_token` to enable certain scenarios that require additional properties
@@ -230,9 +226,7 @@ def get_safe_working_dir() -> str:
230226
if sys.platform.startswith("win"):
231227
path = os.environ.get("SYSTEMROOT")
232228
if not path:
233-
raise CredentialUnavailableError(
234-
message="Environment variable 'SYSTEMROOT' has no value"
235-
)
229+
raise CredentialUnavailableError(message="Environment variable 'SYSTEMROOT' has no value")
236230
return path
237231

238232
return "/bin"
@@ -252,9 +246,7 @@ def _run_command(command_args: List[str], timeout: int) -> str:
252246
# Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway.
253247
if sys.platform.startswith("win"):
254248
# On Windows, the expected executable is az.cmd, so we check for that first, falling back to 'az' in case.
255-
az_path = shutil.which(EXECUTABLE_NAME + ".cmd") or shutil.which(
256-
EXECUTABLE_NAME
257-
)
249+
az_path = shutil.which(EXECUTABLE_NAME + ".cmd") or shutil.which(EXECUTABLE_NAME)
258250
else:
259251
az_path = shutil.which(EXECUTABLE_NAME)
260252
if not az_path:
@@ -277,13 +269,10 @@ def _run_command(command_args: List[str], timeout: int) -> str:
277269
except subprocess.CalledProcessError as ex:
278270
# non-zero return from shell
279271
# Fallback check in case the executable is not found while executing subprocess.
280-
if ex.returncode == 127 or (
281-
ex.stderr is not None and ex.stderr.startswith("'az' is not recognized")
282-
):
272+
if ex.returncode == 127 or (ex.stderr is not None and ex.stderr.startswith("'az' is not recognized")):
283273
raise CredentialUnavailableError(message=CLI_NOT_FOUND) from ex
284274
if ex.stderr is not None and (
285-
("az login" in ex.stderr or "az account set" in ex.stderr)
286-
and "AADSTS" not in ex.stderr
275+
("az login" in ex.stderr or "az account set" in ex.stderr) and "AADSTS" not in ex.stderr
287276
):
288277
raise CredentialUnavailableError(message=NOT_LOGGED_IN) from ex
289278

@@ -297,9 +286,7 @@ def _run_command(command_args: List[str], timeout: int) -> str:
297286
raise ClientAuthenticationError(message=message) from ex
298287
except OSError as ex:
299288
# failed to execute 'cmd' or '/bin/sh'
300-
error = CredentialUnavailableError(
301-
message="Failed to execute '{}'".format(args[0])
302-
)
289+
error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0]))
303290
raise error from ex
304291
except Exception as ex:
305292
# could be a timeout, for example

sdk/identity/azure-identity/azure/identity/aio/_credentials/azure_cli.py

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -106,17 +106,11 @@ async def get_token(
106106
receive an access token.
107107
"""
108108
if claims and claims.strip():
109-
raise CredentialUnavailableError(
110-
f"Fail to get token, please run az login --claims-challenge {claims}"
111-
)
109+
raise CredentialUnavailableError(f"Fail to get token, please run az login --claims-challenge {claims}")
112110

113111
# only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8)
114-
if sys.platform.startswith("win") and not isinstance(
115-
asyncio.get_event_loop(), asyncio.ProactorEventLoop
116-
):
117-
return _SyncAzureCliCredential().get_token(
118-
*scopes, tenant_id=tenant_id, **kwargs
119-
)
112+
if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop):
113+
return _SyncAzureCliCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs)
120114

121115
options: TokenRequestOptions = {}
122116
if tenant_id:
@@ -126,9 +120,7 @@ async def get_token(
126120
return AccessToken(token_info.token, token_info.expires_on)
127121

128122
@log_get_token_async
129-
async def get_token_info(
130-
self, *scopes: str, options: Optional[TokenRequestOptions] = None
131-
) -> AccessTokenInfo:
123+
async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
132124
"""Request an access token for `scopes`.
133125
134126
This is an alternative to `get_token` to enable certain scenarios that require additional properties
@@ -154,9 +146,7 @@ async def get_token_info(
154146
f"Fail to get token, please run az login --claims-challenge {claims_value}"
155147
)
156148
# only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8)
157-
if sys.platform.startswith("win") and not isinstance(
158-
asyncio.get_event_loop(), asyncio.ProactorEventLoop
159-
):
149+
if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop):
160150
return _SyncAzureCliCredential().get_token_info(*scopes, options=options)
161151
return await self._get_token_base(*scopes, options=options)
162152

@@ -207,9 +197,7 @@ async def _run_command(command_args: List[str], timeout: int) -> str:
207197
# Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway.
208198
if sys.platform.startswith("win"):
209199
# On Windows, the expected executable is az.cmd, so we check for that first, falling back to 'az' in case.
210-
az_path = shutil.which(EXECUTABLE_NAME + ".cmd") or shutil.which(
211-
EXECUTABLE_NAME
212-
)
200+
az_path = shutil.which(EXECUTABLE_NAME + ".cmd") or shutil.which(EXECUTABLE_NAME)
213201
else:
214202
az_path = shutil.which(EXECUTABLE_NAME)
215203
if not az_path:
@@ -232,14 +220,10 @@ async def _run_command(command_args: List[str], timeout: int) -> str:
232220
stderr = stderr_b.decode()
233221
except asyncio.TimeoutError as ex:
234222
proc.kill()
235-
raise CredentialUnavailableError(
236-
message="Timed out waiting for Azure CLI"
237-
) from ex
223+
raise CredentialUnavailableError(message="Timed out waiting for Azure CLI") from ex
238224
except OSError as ex:
239225
# failed to execute 'cmd' or '/bin/sh'
240-
error = CredentialUnavailableError(
241-
message="Failed to execute '{}'".format(args[0])
242-
)
226+
error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0]))
243227
raise error from ex
244228

245229
if proc.returncode == 0:

sdk/identity/azure-identity/tests/test_cli_credential.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -400,10 +400,10 @@ def fake_check_output(command_line, **_):
400400
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
401401
def test_claims_challenge_raises_error(get_token_method):
402402
"""The credential should raise CredentialUnavailableError when claims challenge is provided"""
403-
403+
404404
claims = "test-claims-challenge"
405405
expected_message = f"Fail to get token, please run az login --claims-challenge {claims}"
406-
406+
407407
if get_token_method == "get_token":
408408
with pytest.raises(CredentialUnavailableError, match=re.escape(expected_message)):
409409
AzureCliCredential().get_token("scope", claims=claims)
@@ -415,44 +415,46 @@ def test_claims_challenge_raises_error(get_token_method):
415415
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
416416
def test_empty_claims_does_not_raise_error(get_token_method):
417417
"""The credential should not raise error when claims parameter is empty or None"""
418-
418+
419419
# Mock the CLI to avoid actual invocation
420420
with mock.patch("shutil.which", return_value="az"):
421-
with mock.patch(CHECK_OUTPUT, mock.Mock(return_value='{"accessToken": "token", "expiresOn": "2021-10-07 12:00:00.000000"}')):
422-
421+
with mock.patch(
422+
CHECK_OUTPUT, mock.Mock(return_value='{"accessToken": "token", "expiresOn": "2021-10-07 12:00:00.000000"}')
423+
):
424+
423425
if get_token_method == "get_token":
424426
# Test with None (default)
425427
token = AzureCliCredential().get_token("scope")
426428
assert token.token == "token"
427-
429+
428430
# Test with empty string
429431
token = AzureCliCredential().get_token("scope", claims="")
430432
assert token.token == "token"
431-
433+
432434
# Test with None explicitly
433435
token = AzureCliCredential().get_token("scope", claims=None)
434436
assert token.token == "token"
435-
437+
436438
# Test with whitespace-only string
437439
token = AzureCliCredential().get_token("scope", claims=" ")
438440
assert token.token == "token"
439441
else: # get_token_info
440442
# Test with None options
441443
token = AzureCliCredential().get_token_info("scope")
442444
assert token.token == "token"
443-
445+
444446
# Test with empty options
445447
token = AzureCliCredential().get_token_info("scope", options={})
446448
assert token.token == "token"
447-
449+
448450
# Test with None claims in options
449451
token = AzureCliCredential().get_token_info("scope", options={"claims": None})
450452
assert token.token == "token"
451-
452-
# Test with empty string claims in options
453+
454+
# Test with empty string claims in options
453455
token = AzureCliCredential().get_token_info("scope", options={"claims": ""})
454456
assert token.token == "token"
455-
457+
456458
# Test with whitespace-only claims in options
457459
token = AzureCliCredential().get_token_info("scope", options={"claims": " "})
458460
assert token.token == "token"

sdk/identity/azure-identity/tests/test_cli_credential_async.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -394,10 +394,10 @@ async def fake_exec(*args, **_):
394394
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
395395
async def test_claims_challenge_raises_error(get_token_method):
396396
"""The credential should raise CredentialUnavailableError when claims challenge is provided"""
397-
397+
398398
claims = "test-claims-challenge"
399399
expected_message = f"Fail to get token, please run az login --claims-challenge {claims}"
400-
400+
401401
if get_token_method == "get_token":
402402
with pytest.raises(CredentialUnavailableError, match=re.escape(expected_message)):
403403
await AzureCliCredential().get_token("scope", claims=claims)
@@ -409,52 +409,54 @@ async def test_claims_challenge_raises_error(get_token_method):
409409
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
410410
async def test_empty_claims_does_not_raise_error(get_token_method):
411411
"""The credential should not raise error when claims parameter is empty or None"""
412-
413-
successful_output = json.dumps({
414-
"expiresOn": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
415-
"accessToken": "access-token",
416-
"subscription": "subscription",
417-
"tenant": "tenant",
418-
"tokenType": "Bearer",
419-
})
420-
412+
413+
successful_output = json.dumps(
414+
{
415+
"expiresOn": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
416+
"accessToken": "access-token",
417+
"subscription": "subscription",
418+
"tenant": "tenant",
419+
"tokenType": "Bearer",
420+
}
421+
)
422+
421423
# Mock the CLI to avoid actual invocation
422424
with mock.patch("shutil.which", return_value="az"):
423425
with mock.patch(SUBPROCESS_EXEC, mock_exec(successful_output)):
424-
426+
425427
if get_token_method == "get_token":
426428
# Test with None (default)
427429
token = await AzureCliCredential().get_token("scope")
428430
assert token.token == "access-token"
429-
431+
430432
# Test with empty string
431433
token = await AzureCliCredential().get_token("scope", claims="")
432434
assert token.token == "access-token"
433-
435+
434436
# Test with None explicitly
435437
token = await AzureCliCredential().get_token("scope", claims=None)
436438
assert token.token == "access-token"
437-
439+
438440
# Test with whitespace-only string
439441
token = await AzureCliCredential().get_token("scope", claims=" ")
440442
assert token.token == "access-token"
441443
else: # get_token_info
442444
# Test with None options
443445
token = await AzureCliCredential().get_token_info("scope")
444446
assert token.token == "access-token"
445-
447+
446448
# Test with empty options
447449
token = await AzureCliCredential().get_token_info("scope", options={})
448450
assert token.token == "access-token"
449-
451+
450452
# Test with None claims in options
451453
token = await AzureCliCredential().get_token_info("scope", options={"claims": None})
452454
assert token.token == "access-token"
453-
454-
# Test with empty string claims in options
455+
456+
# Test with empty string claims in options
455457
token = await AzureCliCredential().get_token_info("scope", options={"claims": ""})
456458
assert token.token == "access-token"
457-
459+
458460
# Test with whitespace-only claims in options
459461
token = await AzureCliCredential().get_token_info("scope", options={"claims": " "})
460462
assert token.token == "access-token"

0 commit comments

Comments
 (0)