Модульное тестирование Django
Я тестирую свой код django, но чувствую, что мне чего-то не хватает.
Вот вид
@login_required()
def report_incident(request):
template_name = "incident/report_incident.html"
# request.post logic
if request.method == "POST":
form = IncidentForm(request.POST)
if form.is_valid():
# use while loop to generate random unique id
unique = False
while not unique:
id = generate_random_id(15)
if Incident.objects.filter(incident_id=id).first() is None:
unique = True
# Assign unique id to form instance
form.instance.incident_id = id
# get incident type
incident_type = form.instance.incident_type
# If incident type is safeguading issue
if str(incident_type.type).lower() == "safeguarding concerns":
# if form instance of child is none, it means they used the text input
# to write a new child name
if not form.instance.child:
# get the child name from the post request
child_name = request.POST.get('childText')
child_name = str(child_name)
# create child object with new name
unique = False
while not unique:
id = generate_random_id(15)
if Child.objects.filter(child_id=id).first() is None:
unique = True
child = Child.objects.create(child_id = id, name=child_name)
# add new child object to form instance of child
form.instance.child = child
#save form
form.save()
messages.success(request, "Incident reported succesfully")
return redirect("report-incident")
else:
form = IncidentForm()
context = {"form": form}
return render(request, template_name, context)
и вот модульный тест
class TestViews(TestCase):
def setup(self):
self.client = Client()
def test_report_incident_POST(self):
# create user instance
user = User.objects.create_user(username="username", email="email", password="mypassword")
self.client.login(username=user.username, password="mypassword")
# data for incident
employee = Employee.objects.create(employee_id='some_id', name="name")
nursery = Nursery.objects.create(nursery_id="some_id", name="name")
incident_location = IncidentLocation.objects.create(incident_location_id="some_id", nursery=nursery, name="name")
incident_type = IncidentType.objects.create(incident_type_id="some_id", type="type")
response = self.client.post(reverse('report-incident'), {
'employee': employee,
'date_of_incident': date.today(),
'time_of_incident': datetime.now().time(),
'nursery': nursery,
'incident_location': incident_location,
'incident_type': incident_type,
'incident_details': "some data"
})
print(response)
self.assertEquals(response.status_code, 302)
Насколько я понимаю, код состояния ответа этого представления при запросе на пост должен быть 302 из-за переадресации.
Но я получаю ошибку утверждения, потому что код состояния ответа равен 200.
Я знаю, что представление работает, поскольку я получаю перенаправление, мне просто интересно, что я делаю неправильно в файле модульного теста.