I'm trying to write tests for my django app. The tests are failing because I'm getting 302 errors. For CBV I used have a decorator.py file that checks that the user is_teacher
. I believe that this is what is causing the problem.
view
@method_decorator([login_required, teacher_required], name='dispatch')
class ClassroomList(ListView):
model = Classroom
def get_queryset(self):
return Classroom.objects.filter(user=self.request.user).order_by('classroom_name')
model
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
is_student = models.BooleanField('student status', default=False)
is_teacher = models.BooleanField('teacher status', default=False)
def __str__(self):
return self.username
test.py
class GradebookTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username='tester',
email='[email protected]',
password='tester123'
)
self.user.is_active = True
self.user.is_teacher = True
def test_classroomgradebook(self):
self.client.login(username='tester', password='tester123')
response = self.client.get(reverse('gradebook:gradebookstart'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Choose the gradebook')
self.assertNotContains(response, 'Enter')
self.assertTemplateUsed(response, 'gradebook/classroom_list.html')
decorator.py
def teacher_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_teacher,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
If I remove the @method_decorator...
from the view, the test passes.
CodePudding user response:
As @Brian Destur mentioned, you need to call the save()
method of the model to commit the changes to the DB
class GradebookTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username='tester',
email='[email protected]',
password='tester123'
)
self.user.is_active = True
self.user.is_teacher = True
self.user.save() # Save the changes to DB
# your code