Тестирование в Django
Я пытаюсь протестировать свое приложение Django, чтобы получить 100 % покрытие утверждений.
Я использую представление на основе классов и переписываю некоторые функции. Одна из них - форма, действующая в моем AttendanceLogFormView в моем views.py
Мой вопрос в том, как мне проверить, что этот метод работает так, как должен, с помощью модульных тестов в Django? Я очень новичок в тестировании, поэтому мне очень трудно разобраться с концепцией. Я только знаю, что мне нужно проверить if/else для покрытия утверждений - но я не знаю как?
class AttendanceLogFormView(CreateView):
model = AttendanceLog
template_name = "attendancecode/Createattendancelog.html"
form_class = AttendanceLogForm
success_url = "/attendancecode/success/"
# Checks if data input is valid and saves object
def form_valid(self, form):
obj = form.save(commit=False)
user = "nadi6548"
obj.date = date.today()
getClass = Class.objects.get(name=obj.keaclass)
getCourse = Course.objects.get(name=getClass.Course_name)
getLocation = School.objects.get(id=getCourse.location_id)
coords_1 = (getLocation.lat, getLocation.long)
coords_2 = (obj.lat, obj.long)
# check location and that student goes in the class
if (geopy.distance.distance(coords_1, coords_2).km < 0.5) and Student.objects.get(
username=user, Class_id=obj.keaclass):
# check log is a code with correct info and correct date and that
# student has subject + code is active
if AttendanceCode.objects.filter(
code=obj.attendanceCode,
keaclass_id=obj.keaclass,
subject_id=obj.subject_id,
date=obj.date,
isActive="True") and StudentHasSubject.objects.get(
student_name_id=user,
subject_name_id=obj.subject_id):
obj.username_fk = user
obj.save()
return super().form_valid(form)
else:
return render(self.request, './attendancecode/error.html')
else:
return render(self.request, './attendancecode/error.html')
Надеюсь, вы сможете мне помочь, я совсем запутался.
Один из способов - протестировать представление с помощью тестового клиента. Создайте dict для POST к представлению, который будет принимать путь ошибки, а затем протестируйте, что вывод содержит что-то отличное от ./attendancecode/error.html
Что-то вроде
def test0035(self):
c = Client()
login_ok = c.login(username='shipping', password='test') # failed?
self.assertTrue( login_ok)
view_url = ...
expected_in_output = 'A1b2c9'
data = {
'key':'value', ...
# stuff that will satisfy form.is_valid(), but fail the tests
# in your form_valid method
}
response=c.post( view_url, data)
self.assertIn( expected_in_output, response.content.decode() )
Если в шаблоне нет ничего достаточно характерного, вы можете добавить html-комментарий для тестирования. Например, <!-- foo.test0035 A1b2c9, leave this alone -->
и вы можете также вывести значение в этот комментарий foo={{something.foo}}
, если это не повлияет на эффективность производства.
Мне кажется, что то, что вы делаете, может быть лучше закодировано путем преобразования формы без ошибок в форму с ошибками и возвращением form_invalid, как в
if not ( (geopy.distance.distance(coords_1, coords_2).km < 0.5) and Student.objects.get(
username=user, Class_id=obj.keaclass) ):
form.add_error('fieldname', 'Error message')
# fieldname=None for a non_field error
return self.form_invalid( form)