Skip to main content
 首页 » 编程设计

python之使用@patch 装饰器模拟属性

2025年01月19日10zhoujg

我正在为 Python 测试中的模拟属性而苦苦挣扎。我试图测试的函数一直失败,因为模拟可能返回正确的值但类型错误(应该是字符串,而它是 MagicMock。

我找到了这个答案,我知道我需要使用 PropertyMock。但我无法让它与上下文管理器一起工作,也无法使用 @patch 装饰器。 Mock attributes in Python mock?

这是我的测试:

 @patch('keys.views.requests.post') 
 @patch('keys.views.requests.Response.text', new_callable=PropertyMock) 
 def test_shows_message_when_receives_error(self, mock_response_text     ,mock_post): 
 
     expected_error = escape(MESSAGE) 
     data_to_be_received = json.dumps({ 
         "message":"Bad Request", 
         "errors":[{ 
             "resource":"Application", 
             "field":"client_id", 
             "code":"invalid" 
         }] 
     }) 
     mock_response_text.return_value = data_to_be_received 
 
     response = self.client.get('/users/tokenexchange?state=&code=abc123') 
 
     self.assertContains(response, expected_error) 

我正在测试的代码:

def token_exchange(request): 
    parameters = {'client_id': '##', 'client_secret': '##', 'code': code} 
 
    response = requests.post('https://www.strava.com/oauth/token', parameters) 
    data_received = json.loads(response.text) 
 
    if 'errors' not in data_received: 
        return HttpResponse(response.text) 
     else: 
         return render(request, 'home.html', {'error': STRAVA_AUTH_ERROR}) 

我不断收到的错误是:

File "##", line 66, in token_exchange 
    data_received = json.loads(response.text) 
 
TypeError: the JSON object must be str, bytes or bytearray, not 'MagicMock' 

感谢您的回答!!!

请您参考如下方法:

keys.views.requests.Response.text很可能是 instance variable不能也不应该使用 PorpertyMock 来模拟它

这里引用自文档:

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

https://docs.python.org/2/tutorial/classes.html

class Dog: 
 
    kind = 'canine'         # class variable shared by all instances 
 
    def __init__(self, name): 
        self.name = name    # instance variable unique to each instance 

How to mock a python class instance_variable?

我有一个从某处复制的解决方案,它的工作太乏味了:

Python mock a base class's attribute

在您的具体情况下,模拟 Response类而不是 text实例

@patch('keys.views.requests.post') 
@patch('keys.views.requests.Response') 
def test_shows_message_when_receives_error(self, mock_response ,mock_post): 
    mock_post.return_value = None # mock the func 
    mock_response.text = mock.Mock(text=data_to_be_received).text