Skip to content

Commit 0f72615

Browse files
Copilotxiangyan99
andcommitted
Fix black formatting issues with Azure SDK configuration
Co-authored-by: xiangyan99 <[email protected]>
1 parent f19ce6f commit 0f72615

File tree

4 files changed

+55
-171
lines changed

4 files changed

+55
-171
lines changed

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

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,7 @@ def get_token(
156156
return AccessToken(token_info.token, token_info.expires_on)
157157

158158
@log_get_token
159-
def get_token_info(
160-
self, *scopes: str, options: Optional[TokenRequestOptions] = None
161-
) -> AccessTokenInfo:
159+
def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
162160
"""Request an access token for `scopes`.
163161
164162
This is an alternative to `get_token` to enable certain scenarios that require additional properties
@@ -217,9 +215,7 @@ def run_command_line(command_line: List[str], timeout: int) -> str:
217215
try:
218216
proc = start_process(command_line)
219217
stdout, stderr = proc.communicate(**kwargs)
220-
if sys.platform.startswith("win") and (
221-
"' is not recognized" in stderr or proc.returncode == 9009
222-
):
218+
if sys.platform.startswith("win") and ("' is not recognized" in stderr or proc.returncode == 9009):
223219
# pwsh.exe isn't on the path; try powershell.exe
224220
command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1)
225221
proc = start_process(command_line)
@@ -261,12 +257,8 @@ def parse_token(output: str) -> AccessTokenInfo:
261257
return AccessTokenInfo(token, int(expires_on))
262258

263259
if within_dac.get():
264-
raise CredentialUnavailableError(
265-
message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)
266-
)
267-
raise ClientAuthenticationError(
268-
message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)
269-
)
260+
raise CredentialUnavailableError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output))
261+
raise ClientAuthenticationError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output))
270262

271263

272264
def get_command_line(scopes: Tuple[str, ...], tenant_id: str) -> List[str]:

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

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,7 @@ async def get_token(
8888
)
8989

9090
# only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8)
91-
if sys.platform.startswith("win") and not isinstance(
92-
asyncio.get_event_loop(), asyncio.ProactorEventLoop
93-
):
91+
if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop):
9492
return _SyncCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs)
9593

9694
options: TokenRequestOptions = {}
@@ -101,9 +99,7 @@ async def get_token(
10199
return AccessToken(token_info.token, token_info.expires_on)
102100

103101
@log_get_token_async
104-
async def get_token_info(
105-
self, *scopes: str, options: Optional[TokenRequestOptions] = None
106-
) -> AccessTokenInfo:
102+
async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
107103
"""Request an access token for `scopes`.
108104
109105
This is an alternative to `get_token` to enable certain scenarios that require additional properties
@@ -131,9 +127,7 @@ async def get_token_info(
131127
message=f"Fail to get token, please run Connect-AzAccount --ClaimsChallenge {claims_value}"
132128
)
133129

134-
if sys.platform.startswith("win") and not isinstance(
135-
asyncio.get_event_loop(), asyncio.ProactorEventLoop
136-
):
130+
if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop):
137131
return _SyncCredential().get_token_info(*scopes, options=options)
138132
return await self._get_token_base(*scopes, options=options)
139133

@@ -173,9 +167,7 @@ async def run_command_line(command_line: List[str], timeout: int) -> str:
173167
try:
174168
proc = await start_process(command_line)
175169
stdout, stderr = await asyncio.wait_for(proc.communicate(), 10)
176-
if sys.platform.startswith("win") and (
177-
b"' is not recognized" in stderr or proc.returncode == 9009
178-
):
170+
if sys.platform.startswith("win") and (b"' is not recognized" in stderr or proc.returncode == 9009):
179171
# pwsh.exe isn't on the path; try powershell.exe
180172
command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1)
181173
proc = await start_process(command_line)
@@ -193,9 +185,7 @@ async def run_command_line(command_line: List[str], timeout: int) -> str:
193185
error = CredentialUnavailableError(
194186
message='Failed to execute "{}".\n'
195187
"To mitigate this issue, please refer to the troubleshooting guidelines here at "
196-
"https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.".format(
197-
command_line[0]
198-
)
188+
"https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.".format(command_line[0])
199189
)
200190
raise error from ex
201191

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

Lines changed: 22 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,7 @@
3838

3939

4040
def raise_called_process_error(return_code, stdout, stderr="", cmd="..."):
41-
error = subprocess.CalledProcessError(
42-
return_code, cmd=cmd, output=stdout, stderr=stderr
43-
)
41+
error = subprocess.CalledProcessError(return_code, cmd=cmd, output=stdout, stderr=stderr)
4442
return Mock(side_effect=error)
4543

4644

@@ -62,9 +60,7 @@ def test_multiple_scopes(get_token_method):
6260
"""The credential should raise ValueError when get_token is called with more than one scope"""
6361

6462
with pytest.raises(ValueError):
65-
getattr(AzurePowerShellCredential(), get_token_method)(
66-
"one scope", "and another"
67-
)
63+
getattr(AzurePowerShellCredential(), get_token_method)("one scope", "and another")
6864

6965

7066
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
@@ -100,9 +96,7 @@ def test_invalid_scopes(get_token_method):
10096
getattr(AzurePowerShellCredential(), get_token_method)("scope" + c)
10197

10298

103-
@pytest.mark.parametrize(
104-
"stderr,get_token_method", product(("", PREPARING_MODULES), GET_TOKEN_METHODS)
105-
)
99+
@pytest.mark.parametrize("stderr,get_token_method", product(("", PREPARING_MODULES), GET_TOKEN_METHODS))
106100
def test_get_token(stderr, get_token_method):
107101
"""The credential should parse Azure PowerShell's output to an AccessToken"""
108102

@@ -135,9 +129,7 @@ def test_get_token(stderr, get_token_method):
135129
args, kwargs = Popen().communicate.call_args
136130

137131

138-
@pytest.mark.parametrize(
139-
"stderr,get_token_method", product(("", PREPARING_MODULES), GET_TOKEN_METHODS)
140-
)
132+
@pytest.mark.parametrize("stderr,get_token_method", product(("", PREPARING_MODULES), GET_TOKEN_METHODS))
141133
def test_get_token_tenant_id(stderr, get_token_method):
142134
expected_access_token = "access"
143135
expected_expires_on = 1617923581
@@ -160,9 +152,7 @@ def test_ignores_extraneous_stdout_content(get_token_method):
160152
expected_access_token = "access"
161153
expected_expires_on = 1617923581
162154
motd = "MOTD: Customize your experience: save your profile to $HOME/.config/PowerShell\n"
163-
Popen = get_mock_Popen(
164-
stdout=motd + "azsdk%{}%{}".format(expected_access_token, expected_expires_on)
165-
)
155+
Popen = get_mock_Popen(stdout=motd + "azsdk%{}%{}".format(expected_access_token, expected_expires_on))
166156

167157
with patch(POPEN, Popen):
168158
token = getattr(AzurePowerShellCredential(), get_token_method)("scope")
@@ -233,9 +223,7 @@ def test_blocked_by_execution_policy(get_token_method):
233223
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><S S="Error">Import-Module : Errors occurred while loading the format data file: _x000D__x000A_</S><S S="Error">C:\Users\foo\Documents\WindowsPowerShell\Modules\Az.Accounts\2.2.7\Accounts.format.ps1xml, , C:\Users\foo\Documents\WindowsPowerShell\Modules\Az.Accounts\2.2.7\Accounts.format.ps1xml: The file was skipped because of the _x000D__x000A_</S><S S="Error">following validation exception: AuthorizationManager check failed.._x000D__x000A_</S><S S="Error">C:\Users\foo\Documents\WindowsPowerShell\Modules\Az.Accounts\2.2.7\Accounts.generated.format.ps1xml, , C:\Users\foo\Documents\WindowsPowerShell\Modules\Az.Accounts\2.2.7\Accounts.generated.format.ps1xml: The file was skipped _x000D__x000A_</S><S S="Error">because of the following validation exception: AuthorizationManager check failed.._x000D__x000A_</S><S S="Error">At line:4 char:6_x000D__x000A_</S><S S="Error">+ $m = Import-Module Az.Accounts -MinimumVersion $minimumVersion -PassT ..._x000D__x000A_</S><S S="Error">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S><S S="Error"> + CategoryInfo : InvalidOperation: (:) [Import-Module], RuntimeException_x000D__x000A_</S><S S="Error"> + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S></Objs>"""
234224
Popen = get_mock_Popen(return_code=1, stderr=stderr)
235225
with patch(POPEN, Popen):
236-
with pytest.raises(
237-
CredentialUnavailableError, match=BLOCKED_BY_EXECUTION_POLICY
238-
):
226+
with pytest.raises(CredentialUnavailableError, match=BLOCKED_BY_EXECUTION_POLICY):
239227
getattr(AzurePowerShellCredential(), get_token_method)("scope")
240228

241229

@@ -248,9 +236,7 @@ def test_timeout(get_token_method):
248236
proc = Mock(communicate=Mock(side_effect=TimeoutExpired("", 42)), returncode=None)
249237
with patch(POPEN, Mock(return_value=proc)):
250238
with pytest.raises(CredentialUnavailableError):
251-
getattr(AzurePowerShellCredential(process_timeout=42), get_token_method)(
252-
"scope"
253-
)
239+
getattr(AzurePowerShellCredential(process_timeout=42), get_token_method)("scope")
254240

255241
assert proc.communicate.call_count == 1
256242
# Ensure custom timeout is passed to subprocess
@@ -314,23 +300,17 @@ def Popen(args, **kwargs):
314300
stderr = error_message
315301
return_code = 9009
316302
else:
317-
assert args[-1].startswith(
318-
"powershell"
319-
), 'credential should fall back to "powershell"'
303+
assert args[-1].startswith("powershell"), 'credential should fall back to "powershell"'
320304
stdout = NO_AZ_ACCOUNT_MODULE
321305
stderr = ""
322306
return_code = 0
323307

324-
return Mock(
325-
communicate=Mock(return_value=(stdout, stderr)), returncode=return_code
326-
)
308+
return Mock(communicate=Mock(return_value=(stdout, stderr)), returncode=return_code)
327309

328310
with patch(AzurePowerShellCredential.__module__ + ".sys.platform", "win32"):
329311
with patch.dict("os.environ", {"SYSTEMROOT": "foo"}):
330312
with patch(POPEN, Popen):
331-
with pytest.raises(
332-
CredentialUnavailableError, match=AZ_ACCOUNT_NOT_INSTALLED
333-
):
313+
with pytest.raises(CredentialUnavailableError, match=AZ_ACCOUNT_NOT_INSTALLED):
334314
getattr(AzurePowerShellCredential(), get_token_method)("scope")
335315

336316
assert Fake.calls == 2
@@ -343,9 +323,7 @@ def test_multitenant_authentication(get_token_method):
343323
second_token = first_token * 2
344324

345325
def fake_Popen(command, **_):
346-
assert command[-1].startswith(
347-
"pwsh -NoProfile -NonInteractive -EncodedCommand "
348-
)
326+
assert command[-1].startswith("pwsh -NoProfile -NonInteractive -EncodedCommand ")
349327
match = re.search(r"-EncodedCommand\s+(\S+)", command[-1])
350328
assert match, "couldn't find encoded script in command line"
351329
encoded_script = match.groups()[0]
@@ -354,9 +332,7 @@ def fake_Popen(command, **_):
354332
assert match
355333
tenant = match.group(1)
356334

357-
assert not tenant or tenant == second_tenant, 'unexpected tenant "{}"'.format(
358-
tenant
359-
)
335+
assert not tenant or tenant == second_tenant, 'unexpected tenant "{}"'.format(tenant)
360336
token = first_token if not tenant else second_token
361337
stdout = "azsdk%{}%{}".format(token, int(time.time()) + 3600)
362338

@@ -384,9 +360,7 @@ def test_multitenant_authentication_not_allowed(get_token_method):
384360
expected_token = "***"
385361

386362
def fake_Popen(command, **_):
387-
assert command[-1].startswith(
388-
"pwsh -NoProfile -NonInteractive -EncodedCommand "
389-
)
363+
assert command[-1].startswith("pwsh -NoProfile -NonInteractive -EncodedCommand ")
390364
match = re.search(r"-EncodedCommand\s+(\S+)", command[-1])
391365
assert match, "couldn't find encoded script in command line"
392366
encoded_script = match.groups()[0]
@@ -424,23 +398,13 @@ def test_claims_challenge_error(get_token_method):
424398
if get_token_method == "get_token":
425399
# Test claims parameter in get_token method
426400
with pytest.raises(CredentialUnavailableError) as exc_info:
427-
getattr(AzurePowerShellCredential(), get_token_method)(
428-
"scope", claims="some-claims"
429-
)
430-
assert (
431-
"Fail to get token, please run Connect-AzAccount --ClaimsChallenge some-claims"
432-
in str(exc_info.value)
433-
)
401+
getattr(AzurePowerShellCredential(), get_token_method)("scope", claims="some-claims")
402+
assert "Fail to get token, please run Connect-AzAccount --ClaimsChallenge some-claims" in str(exc_info.value)
434403
else:
435404
# Test claims in options for get_token_info method
436405
with pytest.raises(CredentialUnavailableError) as exc_info:
437-
getattr(AzurePowerShellCredential(), get_token_method)(
438-
"scope", options={"claims": "some-claims"}
439-
)
440-
assert (
441-
"Fail to get token, please run Connect-AzAccount --ClaimsChallenge some-claims"
442-
in str(exc_info.value)
443-
)
406+
getattr(AzurePowerShellCredential(), get_token_method)("scope", options={"claims": "some-claims"})
407+
assert "Fail to get token, please run Connect-AzAccount --ClaimsChallenge some-claims" in str(exc_info.value)
444408

445409

446410
@pytest.mark.parametrize("get_token_method", GET_TOKEN_METHODS)
@@ -456,31 +420,21 @@ def test_empty_claims_no_error(get_token_method):
456420
with patch(POPEN, Popen):
457421
if get_token_method == "get_token":
458422
# Test None claims parameter in get_token method
459-
token = getattr(AzurePowerShellCredential(), get_token_method)(
460-
"scope", claims=None
461-
)
423+
token = getattr(AzurePowerShellCredential(), get_token_method)("scope", claims=None)
462424
assert token.token == expected_access_token
463425

464426
# Test empty string claims
465-
token = getattr(AzurePowerShellCredential(), get_token_method)(
466-
"scope", claims=""
467-
)
427+
token = getattr(AzurePowerShellCredential(), get_token_method)("scope", claims="")
468428
assert token.token == expected_access_token
469429
else:
470430
# Test None claims in options for get_token_info method
471-
token = getattr(AzurePowerShellCredential(), get_token_method)(
472-
"scope", options={"claims": None}
473-
)
431+
token = getattr(AzurePowerShellCredential(), get_token_method)("scope", options={"claims": None})
474432
assert token.token == expected_access_token
475433

476434
# Test empty string claims in options
477-
token = getattr(AzurePowerShellCredential(), get_token_method)(
478-
"scope", options={"claims": ""}
479-
)
435+
token = getattr(AzurePowerShellCredential(), get_token_method)("scope", options={"claims": ""})
480436
assert token.token == expected_access_token
481437

482438
# Test missing claims key in options
483-
token = getattr(AzurePowerShellCredential(), get_token_method)(
484-
"scope", options={}
485-
)
439+
token = getattr(AzurePowerShellCredential(), get_token_method)("scope", options={})
486440
assert token.token == expected_access_token

0 commit comments

Comments
 (0)