Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ignore gcloud warning when getting project id #708

Merged
merged 2 commits into from Feb 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions google/auth/_cloud_sdk.py
Expand Up @@ -84,6 +84,13 @@ def get_application_default_credentials_path():
return os.path.join(config_path, _CREDENTIALS_FILENAME)


def _run_subprocess_ignore_stderr(command):
""" Return subprocess.check_output with the given command and ignores stderr."""
with open(os.devnull, "w") as devnull:
output = subprocess.check_output(command, stderr=devnull)
return output


def get_project_id():
"""Gets the project ID from the Cloud SDK.

Expand All @@ -96,9 +103,9 @@ def get_project_id():
command = _CLOUD_SDK_POSIX_COMMAND

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

Expand Down
19 changes: 19 additions & 0 deletions tests/test__cloud_sdk.py
Expand Up @@ -71,6 +71,25 @@ def test_get_project_id_call_error(check_output):
assert check_output.called


def test__run_subprocess_ignore_stderr():
command = [
"python",
"-c",
"from __future__ import print_function;"
+ "import sys;"
+ "print('error', file=sys.stderr);"
+ "print('output', file=sys.stdout)",
]

# If we ignore stderr, then the output only has stdout
output = _cloud_sdk._run_subprocess_ignore_stderr(command)
assert output == b"output\n"

# If we pipe stderr to stdout, then the output is mixed with stdout and stderr.
output = subprocess.check_output(command, stderr=subprocess.STDOUT)
assert output == b"output\nerror\n" or output == b"error\noutput\n"


@mock.patch("os.name", new="nt")
def test_get_project_id_windows():
check_output_patch = mock.patch(
Expand Down