简体   繁体   English

为什么在单元测试期间无法读取环境变量?

[英]why can't read environment variables during unittest?

using vscode + pytest, while the test cases are written in unittest, for example:使用vscode + pytest,而测试用例是用unittest编写的,例如:

class MyTest(unittest.TestCase):
    def testEnvVar(self):
        account = os.getenv("ACCOUNT")

It fails to read ACCOUNT .它无法读取ACCOUNT However, os.getenv("ACCOUNT") will get right result if it's executed by python test.py directly:但是,如果直接由python test.py执行, os.getenv("ACCOUNT")将得到正确的结果:

# test.py
import os
print(os.getenv("ACCOUNT"))

that ensure "ACCOUNT" envar is already set.确保已经设置了“帐户”环境。

If executed by pytest tests/test.py , the envrionment var cannot be read too, so it's caused by pytest.如果由pytest tests/test.py执行,则环境pytest tests/test.py也无法读取,因此是由 pytest 引起的。 I know pytest will do some tricks (for example, pytest will capture all console/stderr output), but I don't know what exactly it does to envar.我知道 pytest 会做一些技巧(例如,pytest 将捕获所有控制台/stderr 输出),但我不知道它究竟对 envar 做了什么。 And same as tox(in tox, you have to set passenv=* , so the test env can inherit all environment variables from shell where tox lives.与 tox 相同(在 tox 中,您必须设置passenv=* ,因此测试环境可以从 tox 所在的 shell 继承所有环境变量。

I mean, I totally understand this is trick that all test-related tools could make, I just don't know how to disable it in pytest.我的意思是,我完全理解这是所有与测试相关的工具都可以制作的技巧,我只是不知道如何在 pytest 中禁用它。 So don't suggest that I have forgot set variable, or my code is wrong, etc.所以不要暗示我忘记了设置变量,或者我的代码是错误的等等。

I know how to hack this, by use mock or add .env vars in vscode launch file.我知道如何破解这个,通过在 vscode 启动文件中使用模拟或添加 .env 变量。 However, this will definitely expose account/password in some files/settings.但是,这肯定会在某些文件/设置中公开帐户/密码。 since account and password are secrets, I don't want to expose them in any files.由于帐户密码是秘密,我不想在任何文件中公开它们。

I guess this is a very common requirement and pytest should have already hornored that.我想这是一个非常普遍的要求,pytest 应该已经意识到了这一点。 So why this still happend?那么为什么这仍然发生呢?

The easiest way is to use https://github.com/MobileDynasty/pytest-env .最简单的方法是使用https://github.com/MobileDynasty/pytest-env But I don't think you should test the enviroment variables in your unit tests.但我认为您不应该在单元测试中测试环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM