我尝试为sqlalchemy(mssql + pyodbc引擎)连接编写测试用例我有以下功能
def test_wrong_password(self):
self.config["DB_Connection"]["password"] = "sdkfajsdklj" #set wrong password
db = db_interaction(self.config["DB_Connection"])
with pytest.raises(sqlalchemy.exc.DBAPIError):
db.getusername("max.mustermann@example.com")
数据库连接的配置存储在配置字典中。在第一个语句中,我将密码更改为一些随机字符串。在第二个语句中,我使用错误的密码初始化db_interaction
的实例。
如果我使用用户xxx
的密码错误运行程序,我会收到以下错误:
sqlalchemy.exc.DBAPIError: (Error) ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'xxx'. (18456) (SQLDriverConnect)") None None
我现在想测试,如果由于密码错误而导致连接被拒绝,而不是由于任何其他异常。 我怎么做到这一点?
答案 0 :(得分:1)
您似乎需要使用此类代码检查异常:
with pytest.raises(DBAPIError) as excinfo:
# code that raises the exception
# code withing 'with' block will fail the test if exception didn't happen at all
# code below will additionally check whether exception was really due to failed login
# please note that it's outside of 'with' block
assert 'Login failed' in excinfo.value
看看: