I am trying to test my Django application to get 100 % statement coverage.
I Am using class-based view and overwriting some af the functionalities. One of them is the form valid in my AttendanceLogFormView in my views.py
My question is how do I test that this method is working as it should with unit tests in Django? I am very new to testing so I very difficult for me to wrap me head around the concept I just know I need to test the if/else for statement coverage - but I don't know how?
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')
Update:
So I found out I can test the model is accepting the create by doing this:
def test_Attendancelog_create(self):
attendancelog = AttendanceLog.objects.create(attendanceCode= -9144444, keaclass= self.Class, subject=self.Subject)
response = self.client.get(reverse('create attendance log'), kwargs={'attendanceCode':attendancelog.attendanceCode})
self.assertEqual(response.status_code, 200)
print(AttendanceLog.objects.last())
self.assertEqual(AttendanceLog.objects.last().date, date.today())
But I want to test the if statements - so does the Attendance log not pass the if statements it should not be created. - so how do I test this functionality?