python - 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')
我会很感激一些帮助!
解决方案
好吧,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
希望有帮助
推荐阅读
- javascript - 将文件夹中的图像加载到 HTML 页面中,以便在添加到文件夹时自动显示在画廊/相册中
- jekyll - 尝试通过 Poole/lanyon 实现 Jekyll,但没有出现格式化
- javascript - axios 响应数据不使用 useState 保存
- c# - 替代监视器来检查记录是否存在,如果不存在则写入
- sql - SQL面试题:选择、加入、分组
- r - 如何在闪亮的应用程序中迭代数据框
- python - 一个空闲的视频/静止帧无缝过渡到一个短动画,然后返回?
- amazon-web-services - 根据不活动从 S3 移动到 S3 Glacier
- loops - Crystal Reports:通过参数将计算数据传递给子报表
- c++ - 使用 Box2D 的 Raycast 进行激光镜像