2013-07-18 8 views
9

मैं पाइथन की mock लाइब्रेरी का उपयोग कर रहा हूं। मैं जानता हूँ कि document का पालन करते हुए एक वर्ग उदाहरण विधि उपहास करने के लिए कैसे:पायथन मॉक क्लास इंस्टेंस वैरिएबल

>>> def some_function(): 
...  instance = module.Foo() 
...  return instance.method() 
... 
>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  result = some_function() 
...  assert result == 'the result' 

हालांकि, एक वर्ग उदाहरण चर नकली की कोशिश की लेकिन (निम्न उदाहरण में instance.labels) काम नहीं करता:

>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  instance.labels = [1, 1, 2, 2] 
...  result = some_function() 
...  assert result == 'the result' 

असल में मैं some_function के तहत इच्छित मूल्य प्राप्त करना चाहता हूं। कोई संकेत?

उत्तर

12

some_function() प्रिंट के इस संस्करण में मज़ाक उड़ाया labels संपत्ति:

def some_function(): 
    instance = module.Foo() 
    print instance.labels 
    return instance.method() 

मेरे module.py:

class Foo(object): 

    labels = [5, 6, 7] 

    def method(self): 
     return 'some' 

पट्टी तुम्हारा रूप में ही है:

with patch('module.Foo') as mock: 
    instance = mock.return_value 
    instance.method.return_value = 'the result' 
    instance.labels = [1,2,3,4,5] 
    result = some_function() 
    assert result == 'the result 

पूर्ण कंसोल सत्र:

>>> from mock import patch 
>>> import module 
>>> 
>>> def some_function(): 
...  instance = module.Foo() 
...  print instance.labels 
...  return instance.method() 
... 
>>> some_function() 
[5, 6, 7] 
'some' 
>>> 
>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  instance.labels = [1,2,3,4,5] 
...  result = some_function() 
...  assert result == 'the result' 
...  
... 
[1, 2, 3, 4, 5] 
>>> 

मेरे लिए आपके कोड काम कर रहा है।

+0

यह काम नहीं करता है। मुझे 'instance.labels = [1, 1, 2, 2]' के समान परिणाम मिला, जो कि यह मॉक वैरिएबल 'some_function' द्वारा उपयोग नहीं किया गया था। प्रलेखन में यह चर के बजाय विधि का मज़ाक उड़ा रहा है। – clwen

+0

मेरा जवाब अपडेट किया गया। अब मैं खो गया हूं क्योंकि आपका कोड काम कर रहा है। – twil

+0

मेरे कोड में, 'लेबल' केवल कुछ फ़ंक्शन कॉल करने के बाद दिखाई देता है। और उस फ़ंक्शन को उस फ़ंक्शन के भीतर बुलाया जाता है जिसे मैं परीक्षण करना चाहता हूं। शायद यही कारण है। मैं कक्षा के प्रारंभिक रूप से नकल करता हूं ताकि यह नकली वस्तु को व्यवहार के साथ वापस कर दे। – clwen

संबंधित मुद्दे