如何将在单元测试中创建的Django Oscar篮子附加到request
对象上?
# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework.response import Response
from rest_framework.views import APIView
class BasketAPIAddView(LoginRequiredMixin, APIView):
"""
Update basket via REST API.
"""
def delete(self, request, format=None):
#
# cannot access `request.basket` here
#
return Response({})
# tests.py
from django.contrib.auth import get_user_model
from django.urls import reverse
from oscar.test.factories import create_basket
from rest_framework.test import APITestCase
User = get_user_model()
class BasketAPITests(APITestCase):
"""
Basket view test cases.
"""
def test_remove_basket_line(self):
basket = create_basket()
basket.owner = User.objects.create_user('user', password='pass')
basket.save()
self.client.login(username='user', password='password')
self.client.delete(reverse('delete-basket'))
答案 0 :(得分:3)
您可以执行以下操作:
Traceback (most recent call last):
File "example-json.py", line 11, in <module>
json_dict = json.loads(data)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 4 column 14 (char 62)
关键是使用请求工厂并随心所欲地添加对象(添加所需内容)。
有关更多详细信息,请查看https://www.django-rest-framework.org/api-guide/testing/
答案 1 :(得分:0)
对于常规请求,oscar.apps.basket.middleware.BasketMiddleware
将篮子添加到请求中,因此可能需要检查测试项目正在使用的settings.MIDDLEWARE
或APITestCase
提供的客户端正在运行中间件。
如果您正在开发API,则可能还需要研究django-oscar-api处理会话管理和中间件的方式。