'str' 对象没有属性 '_encode_json'
'str' object has no attribute '_encode_json'
我一直在用 RequestFactory 编写测试来测试我的一个视图,代码如下:
class ViewTestCase(TestCase):
@classmethod
def setUp(self):
self.factory = RequestFactory
self.user = User.objects.create_user(
first_name='tester',
username='test1',
password='123',
email='testuser@something.com'
)
def test_room_creation(self):
payload = {"titlePlanning": "Test1","styleCards": "Fibonnaci","deck": ["1","2","3"]}
request = self.factory.post('/room', payload)
request.user = self.user
response = BeginRoom.as_view()(request)
self.assertEqual(response.status_code, 200)
这是我需要发送才能使用的数据 POST:
class BeginRoom(APIView):
permissions_classes = (IsAuthenticated,)
def post(self, request, format=None):
data= self.request.data
user = request.user
name = data['titlePlanning'].strip()
styleCards = data['styleCards']
cards = data['deck']
我的问题是,每当我 运行 我的测试时,我都会收到以下错误:
data = self._encode_json({} if data is None else data, content_type)
AttributeError: 'str' object has no attribute '_encode_json'
我该怎么办?我从这里迷路了,找不到任何相关的东西。感谢您的帮助!
而不是里面的这个 test_room_creation
:
request = self.factory.post('/room', payload)
使用这个:
request = self.factory.post('/room', payload, content_type='application/json')
来自docs:
If you provide content_type
as application/json
, the data is serialized using json.dumps()
if it’s a dict, list, or tuple.
我一直在用 RequestFactory 编写测试来测试我的一个视图,代码如下:
class ViewTestCase(TestCase):
@classmethod
def setUp(self):
self.factory = RequestFactory
self.user = User.objects.create_user(
first_name='tester',
username='test1',
password='123',
email='testuser@something.com'
)
def test_room_creation(self):
payload = {"titlePlanning": "Test1","styleCards": "Fibonnaci","deck": ["1","2","3"]}
request = self.factory.post('/room', payload)
request.user = self.user
response = BeginRoom.as_view()(request)
self.assertEqual(response.status_code, 200)
这是我需要发送才能使用的数据 POST:
class BeginRoom(APIView):
permissions_classes = (IsAuthenticated,)
def post(self, request, format=None):
data= self.request.data
user = request.user
name = data['titlePlanning'].strip()
styleCards = data['styleCards']
cards = data['deck']
我的问题是,每当我 运行 我的测试时,我都会收到以下错误:
data = self._encode_json({} if data is None else data, content_type)
AttributeError: 'str' object has no attribute '_encode_json'
我该怎么办?我从这里迷路了,找不到任何相关的东西。感谢您的帮助!
而不是里面的这个 test_room_creation
:
request = self.factory.post('/room', payload)
使用这个:
request = self.factory.post('/room', payload, content_type='application/json')
来自docs:
If you provide
content_type
asapplication/json
, the data is serialized usingjson.dumps()
if it’s a dict, list, or tuple.