1

I am trying to write a python test that involves testing if the environment variables provided are valid. I am passing the environment variables as follows env = EnvironmentVarGuard() env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS) The GOOGLE_CREDENTIALS is an import from a python file. the GOOGLE_CREDENTIALS works while in a .env but once I do the import from a file I receive the following error

self.__credentials = ServiceAccountCredentials.from_json_keyfile_dict(
  File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/service_account.py", line 251, in from_json_keyfile_dict
    return cls._from_parsed_json_keyfile(keyfile_dict, scopes,
  File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/service_account.py", line 185, in _from_parsed_json_keyfile
    signer = crypt.Signer.from_string(private_key_pkcs8_pem)
  File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/oauth2client/_pure_python_crypt.py", line 167, in from_string
    marker_id, key_bytes = pem.readPemBlocksFromFile(
  File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/pyasn1_modules/pem.py", line 44, in readPemBlocksFromFile
    substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines])
  File "/Users/esir/CFA/DebunkBot/venv/lib/python3.8/site-packages/pyasn1_modules/pem.py", line 44, in <listcomp>
    substrate = ''.encode().join([base64.b64decode(x.encode()) for x in certLines])
  File "/Users/esir/.pyenv/versions/3.8.0/lib/python3.8/base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

the part using the env variable is ServiceAccountCredentials.from_json_keyfile_dict(json.loads(os.getenv('GOOGLE_CREDENTIALS'), strict=False), scopes=self.__scope)

so my question is why does it work if I just set the GOOGLE_CREDENTIALS on the .env file but fails if I try using EnvironmentVarGuard

Update Here is how I am using the EnvironmentVarGuard

env = EnvironmentVarGuard()
env.clear()
env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS)
E_K
  • 2,159
  • 23
  • 39

1 Answers1

1

As per the docs I believe you should be using it as a ContextManager as shown below:

from test.support import EnvironmentVarGuard
with EnvironmentVarGuard() as env:
    env.clear()
    env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS)
    # put your code inside context manager
Bernardo Duarte
  • 4,074
  • 4
  • 19
  • 34