2015-04-04 78 views
0

我正在使用py.test和mock。我一直無法嘲諷一個常數。我的測試修改了分配給常量的字典值。這應該在我的測試中引發一個異常,但到目前爲止它沒有。我不確定問題所在,希望能幫助您找出問題所在。謝謝。py.test - 模擬常量並在測試函數中引發異常

the_module.py

MY_DICT = {'one': 1, 'two': 2, 'three': 3}           

class OneMissingException(Exception):            
    pass                   

class Test1(object):                
    def __init__(self):               
     self.mydict = MY_DICT              

    @property                  
    def mydict(self):                
     return self._mydict              

    @mydict.setter                 
    def mydict(self, mydict):              
     if 'one' not in mydict:             
      raise OneMissingException            
     self._mydict = mydict 

test_themodule.py

import pytest                                     
from unittest import mock              
from the_module import Test1, OneMissingException        

@pytest.fixture(scope='function')            
def my_dict():                 
    return {'one': 1, 'two': 2, 'three': 3}          

def test_verify_test1_exception(my_dict):          
    my_dict.pop('one') # comment this out and test still passes              
    with mock.patch("the_module.MY_DICT") as mydict:       
     mydict.return_value.return_value = my_dict        
     with pytest.raises(OneMissingException):        
      Test1() 

回答

2

你的情況,你不需要模擬(你想在一個錯誤的方式來使用它,因爲沒人叫MY_DICT,你試過return_value)

只用pytest的monkeypatch夾具:

import pytest                                     
from unittest import mock              
from the_module import Test1, OneMissingException        

@pytest.fixture            
def patched_my_dict(monkeypatch):                 
    patched = {'one': 1, 'two': 2, 'three': 3} 
    monkeypatch.setattr("the_module.MY_DICT", patched) 
    return patched          

def test_verify_test1_exception(patched_my_dict):          
    patched_my_dict.pop('one') # comment this out and test will not pass              
    with pytest.raises(OneMissingException):        
     Test1() 
+0

謝謝你澄清這一點。不過,我不清楚你的解釋。你能幫我理解我如何錯誤地修改屬性(常量)嗎? – Dowwie 2015-04-04 12:55:55

+0

固定的拼寫錯誤對不起 – 2015-04-04 13:57:37