Skip to content

Commit

Permalink
fix: Correctly catch DefaultCredentialsError when looking up project_…
Browse files Browse the repository at this point in the history
…id (#720)

* Added additional exception catching with unit tests

* lint: fixed spacing

* fix: explicitly force exception raise in unit test
  • Loading branch information
jonathanedey authored Sep 21, 2023
1 parent 59a22b3 commit aef52be
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
3 changes: 2 additions & 1 deletion firebase_admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import os
import threading

from google.auth.exceptions import DefaultCredentialsError
from firebase_admin import credentials
from firebase_admin.__about__ import __version__

Expand Down Expand Up @@ -257,7 +258,7 @@ def _lookup_project_id(self):
if not project_id:
try:
project_id = self._credential.project_id
except AttributeError:
except (AttributeError, DefaultCredentialsError):
pass
if not project_id:
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT',
Expand Down
22 changes: 22 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import os

import pytest
from google.auth.exceptions import DefaultCredentialsError

import firebase_admin
from firebase_admin import credentials
Expand Down Expand Up @@ -315,6 +316,27 @@ def evaluate():
assert app.project_id is None
testutils.run_without_project_id(evaluate)

def test_no_project_id_from_environment(self, app_credential):
default_env = 'GOOGLE_APPLICATION_CREDENTIALS'
gcloud_env = 'CLOUDSDK_CONFIG'
def evaluate():
app = firebase_admin.initialize_app(app_credential, name='myApp')
app._credential._g_credential = None
old_gcloud_var = os.environ.get(gcloud_env)
os.environ[gcloud_env] = ''
old_default_var = os.environ.get(default_env)
if old_default_var:
del os.environ[default_env]
with pytest.raises((AttributeError, DefaultCredentialsError)):
project_id = app._credential.project_id
project_id = app.project_id
if old_default_var:
os.environ[default_env] = old_default_var
if old_gcloud_var:
os.environ[gcloud_env] = old_gcloud_var
assert project_id is None
testutils.run_without_project_id(evaluate)

def test_non_string_project_id(self):
options = {'projectId': {'key': 'not a string'}}
with pytest.raises(ValueError):
Expand Down

0 comments on commit aef52be

Please sign in to comment.