首页 > 解决方案 > AttributeError:“NoneType”对象没有“get”属性,即使我有一个正在使用的类的实例

问题描述

当我运行测试时,如下所示:

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').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')

我会很感激一些帮助!

标签: pythondjango

解决方案


好吧,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

希望有帮助


推荐阅读