我在Python测试中挣扎着嘲弄属性。我试图测试的函数保持失败,因为mock可能返回正确的值但是类型错误(应该是字符串,而不是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'
感谢您的回答!!!
答案 0 :(得分:1)
import React from 'react';
import Body from './Body';
class User extends React.Component {
constructor(props) {
super(props);
this.props = {
employeeCurrent: [],
}
}
极有可能keys.views.requests.Response.text
使用instance variable
不能也不应该嘲笑
以下是文档引用:
一般来说,实例变量用于每个实例的唯一数据,而类变量用于所有类实例共享的属性和方法:
https://docs.python.org/2/tutorial/classes.html
PorpertyMock
如何模拟python类instance_variable?
我有一个从某个地方复制的解决方案,它的工作太繁琐了:
Python mock a base class's attribute
在您的特定情况下,模拟class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
类而不是Response
实例
text