def adminaction(request, item_num): """ Administrative action page Allows user to change status of items. """ chosen_item = get_object_or_404(Item, pk=item_num) status_list = Status.objects.filter(item=item_num) # Perform action on item if request.method == 'POST': form = AdminActionForm(request.POST, current_user=request.user) if form.is_valid(): messages.success(request, "Item successfully changed") form.save(item_pk=item_num, current_user=request.user) return HttpResponseRedirect(request.get_full_path()) else: form = AdminActionForm(current_user=request.user) context = {'item': chosen_item, 'form': form, 'status_list': status_list} return render(request, 'items/admin-action.html', context)
def test_clean_with_errors(self): """ Test 1 - Check that errors appear when returning item with bad data. Test 2 - Check that errors appear when performing other action with bad data. Test 3 - Check that errors appear when action_choice is of type None. """ # Test 1 - Check for errors when returning item. user = create_staff() new_action = Action.objects.get(machine_name=Action.RETURNED) data = {'action_choice': new_action, 'note': "", 'first_name': "", 'last_name': "", 'email': "", } with patch('its.items.forms.AdminActionForm.clean', return_value=data): with patch("its.items.forms.AdminActionForm.add_error") as add_error: form = AdminActionForm(data, current_user=user) form.clean() add_error.assert_any_call_with("first_name", "First name is required when returning item.") add_error.assert_any_call_with("last_name", "Last name is required when returning item.") add_error.assert_any_call_with("email", "Email is required when returning item.") # Test 2 - Check for errors when selecting other action. new_action = Action.objects.get(machine_name=Action.OTHER) data = {'action_choice': new_action, 'note': "", 'first_name': "", 'last_name': "", 'email': "", } with patch('its.items.forms.AdminActionForm.clean', return_value=data): with patch("its.items.forms.AdminActionForm.add_error") as add_error: form = AdminActionForm(data, current_user=user) form.clean() add_error.assert_any_call_with("note", "Note required when choosing action of type Other.") # Test 3 - Check for errors when action_choice not in dictionary. # Failed as NoneType AttributeError for machine_name in clean on old code. user = create_user() data = {'action_choice': None, 'note': "", 'first_name': "", 'last_name': "", 'email': "", } form = AdminActionForm(data, current_user=user) self.assertFalse(form.is_valid())