Skip to content

Commit 3f2f3ea

Browse files
fix: ignore gcloud warning when getting project id (#708)
* fix: ignore gcloud warning when getting project id * update
1 parent 65074d3 commit 3f2f3ea

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

google/auth/_cloud_sdk.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,13 @@ def get_application_default_credentials_path():
8484
return os.path.join(config_path, _CREDENTIALS_FILENAME)
8585

8686

87+
def _run_subprocess_ignore_stderr(command):
88+
""" Return subprocess.check_output with the given command and ignores stderr."""
89+
with open(os.devnull, "w") as devnull:
90+
output = subprocess.check_output(command, stderr=devnull)
91+
return output
92+
93+
8794
def get_project_id():
8895
"""Gets the project ID from the Cloud SDK.
8996
@@ -96,9 +103,9 @@ def get_project_id():
96103
command = _CLOUD_SDK_POSIX_COMMAND
97104

98105
try:
99-
output = subprocess.check_output(
100-
(command,) + _CLOUD_SDK_CONFIG_COMMAND, stderr=subprocess.STDOUT
101-
)
106+
# Ignore the stderr coming from gcloud, so it won't be mixed into the output.
107+
# https://github.com/googleapis/google-auth-library-python/issues/673
108+
output = _run_subprocess_ignore_stderr((command,) + _CLOUD_SDK_CONFIG_COMMAND)
102109
except (subprocess.CalledProcessError, OSError, IOError):
103110
return None
104111

tests/test__cloud_sdk.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,25 @@ def test_get_project_id_call_error(check_output):
7171
assert check_output.called
7272

7373

74+
def test__run_subprocess_ignore_stderr():
75+
command = [
76+
"python",
77+
"-c",
78+
"from __future__ import print_function;"
79+
+ "import sys;"
80+
+ "print('error', file=sys.stderr);"
81+
+ "print('output', file=sys.stdout)",
82+
]
83+
84+
# If we ignore stderr, then the output only has stdout
85+
output = _cloud_sdk._run_subprocess_ignore_stderr(command)
86+
assert output == b"output\n"
87+
88+
# If we pipe stderr to stdout, then the output is mixed with stdout and stderr.
89+
output = subprocess.check_output(command, stderr=subprocess.STDOUT)
90+
assert output == b"output\nerror\n" or output == b"error\noutput\n"
91+
92+
7493
@mock.patch("os.name", new="nt")
7594
def test_get_project_id_windows():
7695
check_output_patch = mock.patch(

0 commit comments

Comments
 (0)