AttributeError:即使我有正在使用的类的实例,“ NoneType”对象也没有属性“ get”

时间:2019-04-19 14:30:11

标签: python django

运行测试时,如下所示:

def test_match_data_while_updating(self):
    match_updated_data = {
        'id': 1,
        'status': 'not_started',
    }    
    match = Match.objects.first()

    # TST N.1 : status not_started
    # -------
    match.status = 'not_started'
    request = self.__class__.factory.put('', match_updated_data, format='json')        
    add_authentication_to_request(request, is_staff=True)
    response = update_match_video(request)
    self.assertEqual(Match.objects.first().status,'live')

我看到错误消息:

  

print('request data get match:',request.data.get('match')。get('id'))

     

AttributeError:'NoneType'对象没有属性'get'

这是我正在测试的功能:

def update_match_video(request):
   print('request data get match: ',request.data.get('match').get('id'))
   if not request.data.get('match').get('id'):
     return JsonResponse({}, status=status.HTTP_400_BAD_REQUEST)

   try:
     match_id = valid_data_or_error(request.data, method='PUT')['match_data']['id']
     match = Match.objects.get(id = match_id)
     db_match_status = match.status

     if db_match_status == 'live':
        valid_data_or_error(request.data, method='PUT')['match_data']['status'] = 'live'
     else:
        if db_match_status == 'closed':
            valid_data_or_error(request.data, method='PUT')['match_data']['status'] = 'closed'
   except Match.DoesNotExist:
      print('Match does  not exist')

请多多帮助!

1 个答案:

答案 0 :(得分:0)

好吧,request.data为None:

确定要命中带有请求参数的函数的一种方法是使用Django的测试客户端,并确定PT您期望的值:

from django.test import Client
from django.test import TestCase
... other import as needed

class TestMyFunc(TestCase):
    def setUp(self):
        self.client = Client()

    def test_match_data_while_updating(self):
        match_updated_data = {
        'id': 1,
        'status': 'not_started',
        }    
        match = Match.objects.first()

        # TST N.1 : status not_started
        # -------
        match.status = 'not_started'
        response = self.client.put( .... ) ## JSON of put data -- make certain to PUT "{ .., match: "something!", ..}
        self.assertEqual(response.status_code, 200)
        ... other assertions

现在,这将创建一个测试数据库(并且应该没有副作用(单元测试,而不是集成测试))并且可以可靠地重复。

要让django运行此测试,请将其放在主项目目录下的tests目录中(与视图,模型等相邻),然后执行python manage.py run tests

希望有帮助