Unit test app using local JSON for GCP authentication?

Viewed 21

I want to Unit test a some FastAPI API endpoints which utilizes Google Cloud Platfrom, I want to write the test without using os.environ["GOOGLE_APPLICATION_CREDENTIALS"]='path_to_json_file.json' in the files to authenticate (as this service will be in the cloud soon). Is there a way to mock this?

1 Answers

It's slightly unclear from your question but it is unlikely that you would ever want to set GOOGLE_APPLICATION_CREDENTIALS from within your code, partly for this reason.

You should set the variable from the environment:

GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
python3 your_code.py

Application Default Credentials (ADC) looks for credentials in 3 locations:

  1. GOOGLE_APPLICATION_DEFAULT environment variable
  2. gcloud application-default login
  3. The compute service's identity

For this reason, setting the variable explicitly in code, overrides the possibility of #2 (less important) and #3 (more important).

If you set the variable outside of the code when you run the code for testing etc., the credentials will be found automatically and the code will be auth'd.

When you don't set the variable because the code is running on a compute service (e.g. Cloud Run, Compute Engine ...), the service's credentials will be used automatically by ADC and the code will be auth'd.

Related