gpt4 book ai didi

python - 如何防止pytest在测试期间打印局部变量

转载 作者:行者123 更新时间:2023-12-04 16:46:12 25 4
gpt4 key购买 nike

我正在使用 pytest 执行一个简单的测试脚本。我正在测试创建数据库连接是否成功。
创建数据库连接的函数需要用户名和密码。在测试过程中,pytest 会打印出用户名和密码。显然,我不希望将密码打印到控制台!我怎样才能防止这种情况发生?

我尝试了多种解决方案,包括使用 contextlib 和自定义创建的 NullWriters 来抑制 stderr 和/或 stdout(例如这里 https://stackoverflow.com/a/1810086 )。然而,似乎没有任何效果。

这是测试功能:

def test_make_db2_connection():

# get username and password from the environmental variables
username = os.environ['username']
password = 'my_password' # would be: os.environ['pwd']

# create a connection with the database
connection = make_db2_connection(username, password)

# assert if the connection exists
assert connection, "Connection wasn't created."

请参阅下面的 pytest 输出。如您所见,打印了我的用户名和(测试)密码。这是我想要防止的。
============================================================================================================ FAILURES ============================================================================================================
____________________________________________________________________________________________________ test_make_db2_connection ____________________________________________________________________________________________________

def test_make_db2_connection():

# get username and password from the environmental variables
username = os.environ['username']
password = 'my_password' # would be: os.environ['pwd']

# create a connection with the database
> connection = make_db2_connection(username, password)

test_file.py:16:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

username = 'E001703', password = 'my_password'

def make_db2_connection(username, password):
"""Creates a connection with the database"""

dbalias = os.environ['dbalias']
> connection = connect(dbalias, username, password)
SQLCODE=-30082on: [IBM][CLI Driver] SQL30082N Security processing failed with reason "24" ("USERNAME AND/OR PASSWORD INVALID"). SQLSTATE=08001

=================================================================================================== 1 failed in 14.19 seconds ====================================================================================================

最佳答案

由@hoefling 解决!请参阅原始问题下方的评论。

解决方案是使用 __tracebackhide__ = True .此解决方案的缺点是您需要修改正在测试的原始函数,而不是测试脚本本身。

关于python - 如何防止pytest在测试期间打印局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56324275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com