我正在用pytest执行一个简单的测试脚本。我正在测试数据库连接的创建是否成功。 创建数据库连接的函数需要用户名和密码。在测试过程中,pytest打印出用户名和密码。显然,我不希望将密码打印到控制台上!如何防止这种情况发生?
我尝试了多种解决方案,包括使用contextlib和自定义创建的NullWriter(可抑制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 ====================================================================================================
答案 0 :(得分:0)
由@hoefling解决!请参阅原始问题下方的评论。
解决方案是使用__tracebackhide__ = True
。该解决方案的缺点是您需要修改要测试的原始功能,而不是测试脚本本身。