2013-08-21 22 views
1

感謝您提前給予的幫助。Python:assertRaises()在引發時不會捕獲ldap.SERVER_DOWN錯誤

我有下面的類的方法,我試圖測試一下:

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()) 

到目前爲止,一切都很好。但是當我執行單元測試(通過鼻子)test_extractor._get_ldap_connection()是從assertRaises語句中調用的,但是異常沒有被捕獲並且測試失敗。

這裏是輸出:

[email protected]:/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 

幫幫我吧!

回答

1

不要調用,只是傳遞函數(方法)本身;降()

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

**是**,當然。我多麼愚蠢。謝謝@falsetru。我會標記你的答案是正確的。 – eikonomega

+0

@eikonomega,不客氣。這是我最喜歡的(?)錯誤之一。 ;) – falsetru

1

您沒有使用正確assertRaises

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() 

或通常的方式(self.assertRaises(exception, function, args)

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

另見: