Skip to content

Commit 84599aa

Browse files
feat: Log the flow.run_local_server redirect URL (#362)
When running this library in a headless environment, it's often the case that `print` is not captured and delivered to the end user. By **also** logging the `auth_url`, a user of this library could ensure that the auth url reaches the logs. --------- Co-authored-by: Chalmer Lowe <[email protected]>
1 parent f41f891 commit 84599aa

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

packages/google-auth-oauthlib/google_auth_oauthlib/flow.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,7 @@ def run_local_server(
447447
webbrowser.get(browser).open(auth_url, new=1, autoraise=True)
448448

449449
if authorization_prompt_message:
450+
_LOGGER.info(authorization_prompt_message.format(url=auth_url))
450451
print(authorization_prompt_message.format(url=auth_url))
451452

452453
local_server.timeout = timeout_seconds

packages/google-auth-oauthlib/tests/unit/test_flow.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import datetime
1717
from functools import partial
1818
import json
19+
import logging
1920
import os
2021
import re
2122
import socket
@@ -460,3 +461,38 @@ def test_local_server_socket_cleanup(
460461
instance.run_local_server()
461462

462463
server_mock.server_close.assert_called_once()
464+
465+
@mock.patch("builtins.print")
466+
@mock.patch("google_auth_oauthlib.flow.webbrowser", autospec=True)
467+
def test_run_local_server_logs_and_prints_url(
468+
self, webbrowser_mock, print_mock, instance, mock_fetch_token, port, caplog
469+
):
470+
auth_redirect_url = urllib.parse.urljoin(
471+
f"http://localhost:{port}", self.REDIRECT_REQUEST_PATH
472+
)
473+
474+
# Configure caplog to capture INFO logs
475+
caplog.set_level(logging.INFO, logger="google_auth_oauthlib.flow")
476+
477+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
478+
future = pool.submit(partial(instance.run_local_server, port=port))
479+
480+
while not future.done():
481+
try:
482+
requests.get(auth_redirect_url)
483+
except requests.ConnectionError:
484+
pass
485+
486+
future.result()
487+
488+
# Verify log message
489+
assert "Please visit this URL" in caplog.text
490+
assert urllib.parse.quote(instance.redirect_uri, safe="") in caplog.text
491+
492+
# Verify print message
493+
print_mock.assert_called_once()
494+
assert "Please visit this URL" in print_mock.call_args[0][0]
495+
assert (
496+
urllib.parse.quote(instance.redirect_uri, safe="")
497+
in print_mock.call_args[0][0]
498+
)

0 commit comments

Comments
 (0)