I am trying to test my view using RequestFactory(). However, calling this view in the test responded as None:
def add_to_basket(request):
cart = Cart(request)
if request.POST.get('action') == 'post':
# GETS game DATA FROM AJAX REQUEST
game_id = request.POST.get('gameId')
game_qty = int(request.POST.get('gameQty'))
# check if game exists
try:
game = Game.objects.get(pk=game_id)
except Game.DoesNotExist:
return JsonResponse({'message': 'Game not found'})
# CHECKS IF ANY OPEN ORDER
order_qs = Order.objects.filter(ordered=False)
if order_qs.exists():
# CHECK IF GAME ALREADY ADDED
order = order_qs[0]
add_new_item_to_order(request,
game_qty,
game,
order)
else:
# create new order
order = Order.objects.create()
add_new_item_to_order(request,
game_qty,
game,
order)
# ADDS GAME TO SESSION DICT
actual_qty = order.items.get(item_id=game_id).quantity
cart.add(game, actual_qty)
# get total QTY of basket
cart_length = cart.__len__()
# message
if game_qty != actual_qty:
return JsonResponse({'message': 'Item quantity was adjusted!', 'total': order.total, 'qty': cart_length, 'instock': False})
elif game.quantity_available == 0:
return JsonResponse({'message': 'Item was added', 'total': order.total, 'qty': cart_length, 'instock': False})
return JsonResponse({'message': 'Item was added', 'total': order.total, 'qty': cart_length})
def setUp(self) -> None:
# request factory
self.factory = RequestFactory()
self.middleware = SessionMiddleware()
def test_add_to_basket(self):
# set sessions middleware
request = self.factory.post(reverse('order:add-to-cart'))
self.middleware.process_request(request)
request.session.save()
# request.user = self.test_user
response = add_to_basket(request)
print(response.status_code)
print(response.content)
Printing response outputs None - though apart test, view is working as expected. What could cause this?
okay. I got it. I forgot to pass 'action' variable in post request request = self.factory.post(reverse('order:add-to-cart'))
- should be : request = self.factory.post(reverse('order:add-to-cart'), data={'action': 'post', ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.