diff --git a/google/auth/_cloud_sdk.py b/google/auth/_cloud_sdk.py index e772fe964..40e6aec13 100644 --- a/google/auth/_cloud_sdk.py +++ b/google/auth/_cloud_sdk.py @@ -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. @@ -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 diff --git a/tests/test__cloud_sdk.py b/tests/test__cloud_sdk.py index 337760426..31cb6c22c 100644 --- a/tests/test__cloud_sdk.py +++ b/tests/test__cloud_sdk.py @@ -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(