2012-03-23 9 views
10

का उपयोग कर एक परीक्षण परीक्षण मामले में assertRaises का उपयोग कैसे करें।मैं यह पता लगाने की कैसे एक परीक्षण के परीक्षण का मामला जो एक अपवाद उठाया है का दावा है लिखने के लिए कोशिश कर रहा हूँ inlineCallbacks

वर्तमान में मैं परीक्षण करने के लिए 2 सरल तरीके (सफलता और विफलता) है। प्रत्येक विधि एक स्थगित लौटाती है जो पहले से ही कॉलबैक या त्रुटि हुई है। सफलता विधि का परीक्षण ठीक काम करता है। विफलता विधि का परीक्षण करते समय मैं यह कहने में सक्षम होने की उम्मीद करता हूं कि एक अपवाद उठाया गया था (assertRaises का उपयोग करके)।

हालांकि परीक्षण मामले में विफल रहता है और मैं:

 
from twisted.trial.unittest import TestCase 
from twisted.internet.defer import inlineCallbacks, succeed, fail 
from twisted.internet.error import ConnectionRefusedError 

class MyObject: 
    def success(self): 
     return succeed(True) 

    def failure(self): 
     return fail(ConnectionRefusedError()) 


class TestErrBack(TestCase): 
    def setUp(self): 
     self.o = MyObject() 

    @inlineCallbacks 
    def test_success(self): 
     result = yield self.o.success() 
     self.assertTrue(result) 

    @inlineCallbacks 
    def test_failure(self): 
     # this test case is failing ! 
     yield self.assertRaises(ConnectionRefusedError, self.o.failure) 

मैं test_failure में सही दृष्टिकोण का उपयोग कर रहा हूँ:

 
twisted.trial.unittest.FailTest: ConnectionRefusedError not raised (<Deferred at 0x920e28c current result: <twisted.python.failure.Failure <class 'twisted.internet.error.ConnectionRefusedError'>>> returned) 

कोड इस प्रकार है? मैं कोशिश कर सकता हूं ... self.o.failure पर कॉल के चारों ओर पकड़ो, लेकिन मुझे नहीं लगता कि यह दृष्टिकोण assertRaises का उपयोग करने के समान अच्छा है। बजाय

उत्तर

13

उपयोग TestCase.assertFailure:

self.failureResultOf(self.o.failure()).trap(ConnectionRefusedError) 

और 13.1 में शुरू होने वाले इस एपीआई एक अतिरिक्त तर्क लेता है और आप के लिए जाँच टाइप करता है:

yield self.assertFailure(self.o.failure(), ConnectionRefusedError) 

मुड़ 12.3 की शुरुआत में, यह भी एक TestCase.failureResultOf सहायक है:

self.failureResultOf(self.o.failure(), ConnectionRefusedError) 

यह हम हैं परीक्षणों के लिए उत्सुक है जहां आप जानते हैंDeferred पहले ही परिणाम से निकाल दिया गया है। यदि Deferred में कॉल के समय विफलता परिणाम नहीं है, तो failureResultOf विफलता को वापस करने के बजाय परीक्षण-विफल अपवाद उठाता है।

यह आपके उदाहरण कोड के लिए ठीक से काम करेंगे और सबसे इकाई परीक्षण के लिए लागू किया जाना चाहिए। यदि आप कार्यात्मक या एकीकरण परीक्षण लिखने के लिए परीक्षण का उपयोग कर रहे हैं जहां वास्तविक असीमित काम चल रहा है और आपको नहीं पता कि Deferred आग लग जाएगी तो आपको पहले एपीआई, assertFailure के साथ चिपकने की आवश्यकता होगी।

+1

धन्यवाद, यह वही है जो मैं ढूंढ रहा था! –