gpt4 book ai didi

Python:assertRaises()在引发时未捕获ldap.SERVER_DOWN错误

转载 作者:行者123 更新时间:2023-12-01 05:38:10 25 4
gpt4 key购买 nike

感谢您提前提供的帮助。

我正在尝试测试以下类方法:

def _get_ldap_connection(self):
"""
Instantiate and return simpleldap.Connection object.

Raises:
ldap.SERVER_DOWN: When ldap_url is invalid or server is
not reachable.

"""
try:
ldap_connection = simpleldap.Connection(
self.ldap_url, encryption='ssl', require_cert=False,
debug=False, dn=self.ldap_login_dn,
password=self.ldap_login_password)

except ldap.SERVER_DOWN:
raise ldap.SERVER_DOWN(
"The LDAP server specified, {}, did not respond to the "
"connection attempt.".format(self.ldap_url))

这是单元测试:

def test__get_ldap_connection(self):
"""
VERY IMPORTANT: This test refers to your actual config.json file.
If it is correctly populated, you can expect this test to fail.

"""

# Instantiate Class
test_extractor = SakaiLdapExtractor('config_files/config.json')

# Monkey with ldap server url to ensure error.
test_extractor.ldap_url = "invalid_ldap_url"

self.assertRaises(
ldap.SERVER_DOWN, test_extractor._get_ldap_connection())

到目前为止,一切都很好。但是当我执行单元测试时(通过 Nose )从assertRaises语句调用test_extractor._get_ldap_connection(),但异常没有被捕获并且测试失败。

这是输出:

vagrant@precise64:/vagrant/sakai-directory-integration$ nosetests
...E..
======================================================================
ERROR: VERY IMPORTANT: This test refers to your actual config.json file.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/vagrant/sakai-directory-integration/test_sakaiLdapExtractor.py", line 77, in test__get_ldap_connection
ldap.SERVER_DOWN, test_extractor._get_ldap_connection())
File "/vagrant/sakai-directory-integration/sakai_ldap_integration.py", line 197, in _get_ldap_connection
"connection attempt.".format(self.ldap_url))
SERVER_DOWN: The LDAP server specified, invalid_ldap_url, did not respond to the connection attempt.

----------------------------------------------------------------------
Ran 6 tests in 0.159s

帮帮我!

最佳答案

不调用,只传递函数(方法)本身;删除():

self.assertRaises(
ldap.SERVER_DOWN, test_extractor._get_ldap_connection)

或者,如果您使用的是最新版本的 python(Python 2.7+/Python 3.1+),则可以使用 with self.assertRaises(..) 形式:

with self.assertRaises(ldap.SERVER_DOWN):
test_extractor._get_ldap_connection()

关于Python:assertRaises()在引发时未捕获ldap.SERVER_DOWN错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18360198/

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