我正在尝试编写一个python测试,其中涉及测试所提供的环境变量是否有效。我按如下方式传递环境变量
env = EnvironmentVarGuard()
env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS)
GOOGLE_CREDENTIALS
是从python文件导入的。
GOOGLE_CREDENTIALS
在.env
中有效,但是一旦我从文件中导入,就会收到以下错误消息
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
使用env变量的部分是
ServiceAccountCredentials.from_json_keyfile_dict(json.loads(os.getenv('GOOGLE_CREDENTIALS'), strict=False), scopes=self.__scope)
所以我的问题是,如果我仅在GOOGLE_CREDENTIALS
文件上设置.env
,为什么会起作用,但是如果我尝试使用EnvironmentVarGuard
更新 这是我使用EnvironmentVarGuard的方式
env = EnvironmentVarGuard()
env.clear()
env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS)
答案 0 :(得分:1)
根据docs,我相信您应该将其用作ContextManager,如下所示:
from test.support import EnvironmentVarGuard
with EnvironmentVarGuard() as env:
env.clear()
env.set('GOOGLE_CREDENTIALS', GOOGLE_CREDENTIALS)
# put your code inside context manager