Python unittest 无法访问 PyCharm 中的本地环境变量

jam*_*mes 6 python pycharm python-unittest

这实在是难倒了我。当我将 API 密钥设置为环境变量,然后尝试使用使用此 API 密钥的 unittest 运行测试时,该测试无法访问该 API 密钥。我不想在测试本身中设置环境变量,因为该值是秘密的,并且我不希望它被我的 VCS 意外跟踪。

$ export API_KEY=hunter2
$ python -m unittest discover tests

    ERROR: setUpClass (tests_system.TestInit)

----------------------------------------------------------------------

Traceback (most recent call last):

  File "/home/travis/build/jamesbrunet/callhub-python-wrapper/callhub/auth.py", line 23, in __init__

    self.api_key = os.environ["API_KEY"]

  File "/home/travis/virtualenv/python3.5.6/lib/python3.5/os.py", line 725, in __getitem__

    raise KeyError(key) from None

KeyError: 'API_KEY'
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我只运行一个测试文件,python test-file.py它就会成功执行并且可以访问 API 密钥。我只有在使用时才会遇到这个问题python -m unittest discover <directory of test file>。不幸的是,我需要使用后一个命令来发现目录中的所有测试文件。

unittest 的文档没有引用环境变量,所以我对这里发生的事情有点不知所措。

编辑:我在本地计算机上做了一些额外的测试,这个问题的范围似乎仅限于在 PyCharm 和 Travis 中运行这些命令。这两者都使用虚拟环境。也许这与 @AndrewAllaire 对这篇文章的评论有关?

jam*_*mes 0

我还没有解决这个谜团unittest discover,但如果你是一个来自谷歌的谨慎的未来旅行者,并且穿着闪亮盔甲的骑士似乎没有拯救世界,这个简陋的解决方法将解决这个问题:

python -m unittest tests.file_1
python -m unittest tests.file_2
python -m unittest tests.file_n
Run Code Online (Sandbox Code Playgroud)

如果使用工作服来监控测试覆盖率,您可以像这样执行测试,它们将正确执行并显示您的组合代码覆盖率:

  coverage run --parallel-mode --source=sourcedir -m unittest tests.file_1
  coverage run --parallel-mode --source=sourcedir -m unittest tests.file_2
  coverage run --parallel-mode --source=sourcedir -m unittest tests.file_n
  coverage combine
Run Code Online (Sandbox Code Playgroud)

这不太好,所以我祈祷我们能从对 python-unittest 有更多经验的人那里得到解决方案。