AssertionError: 403 != 200

Hello everybody. I wrote the following view:

class PacienteCreateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView):
    model = models.Paciente
    fields = ["cedula", "nombre", "apellido", "sexo", "fecha_de_nacimiento"]
    success_message = '''Paciente registrado satisfactoriamente.'''
    permission_required = "can_add_paciente"

    def get_success_url(self):
        return reverse('paciente_list')

and this the test:

class PacienteCreateViewTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.view_url = reverse('paciente_add')
        cls.redirect_url = reverse("paciente_list")
        cls.redirect_url_not_logged = "/accounts/login/?next=/consultorio/paciente/add/"
        cls.user = CustomUser.objects.create_user(
            email="doctor@ejemplo.com",
            first_name="doctor",
            last_name="ejemplo",
            sexo="F",
            password="nucote77",
        )

        user_group = Group.objects.get_or_create(name='Doctores')
        permission = Permission.objects.get(codename="add_paciente")
        user_group[0].user_set.add(cls.user)
        cls.user_data = {
            "username": "doctor@ejemplo.com",
            "password": "nucote77"
            }

        cls.paciente_data = {
            "cedula": "3242918",
            "nombre": "Carmen",
            "apellido": "GarcĂ­a",
            "sexo": "F",
            "fecha_de_nacimiento": "1947-03-29"
        }

    def setUp(self):
        self.client.login(**self.user_data)
        self.response = self.client.get(self.view_url)

    def test_url_exists_at_correct_location(self):
        self.assertEqual(self.view_url, "/consultorio/paciente/add/")

    def test_url_available_by_name(self):
        self.assertEqual(self.response.status_code, 200)

    def test_view_template(self):
        self.assertTemplateUsed(self.response, 'consultorio/paciente_form.html')
        self.assertTemplateNotUsed(self.response, 'plantilla,html')
        self.assertContains(self.response, '<p>Agregar Nuevo Paciente</p>')
        self.assertNotContains(self.response, 'Hi there')

    def test_view_name(self):
        view = resolve(self.view_url)
        self.assertEqual(view.func.__name__, PacienteCreateView.as_view().__name__)

    def test_post_sucess(self):
        response = self.client.post(self.view_url, data=self.paciente_data)
        self.assertEquals(response.status_code, 200)
        self.assertRedirects(response, self.redirect_url)

    def test_redirects_if_user_not_logged(self):
        self.client.logout()
        response = self.client.get(self.view_url)
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, self.redirect_url_not_logged)

and it is throwing this error:

$ py manage.py test consultorio.test.test_views.PacienteCreateViewTests
Creating test database for alias 'default'...
Found 6 test(s).
System check identified no issues (0 silenced).
F.F..F
======================================================================
FAIL: test_post_sucess (consultorio.test.test_views.PacienteCreateViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\goyo\Documents\django\proyecto_consultorio\consultorio\test\test_views.py", line 118, in test_post_sucess
    self.assertEquals(response.status_code, 200)
AssertionError: 403 != 200

======================================================================
FAIL: test_url_available_by_name (consultorio.test.test_views.PacienteCreateViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\goyo\Documents\django\proyecto_consultorio\consultorio\test\test_views.py", line 104, in test_url_available_by_name
    self.assertEqual(self.response.status_code, 200)
AssertionError: 403 != 200

======================================================================
FAIL: test_view_template (consultorio.test.test_views.PacienteCreateViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\goyo\Documents\django\proyecto_consultorio\consultorio\test\test_views.py", line 107, in test_view_template
    self.assertTemplateUsed(self.response, 'consultorio/paciente_form.html')
  File "C:\Users\goyo\Documents\django\proyecto_consultorio\.venv_consultorio\lib\site-packages\django\test\testcases.py", line 859, in assertTemplateUsed
    self._assert_template_used(template_name, template_names, msg_prefix, count)
  File "C:\Users\goyo\Documents\django\proyecto_consultorio\.venv_consultorio\lib\site-packages\django\test\testcases.py", line 823, in _assert_template_used
    self.fail(msg_prefix + "No templates used to render the response")
AssertionError: No templates used to render the response

----------------------------------------------------------------------
Ran 6 tests in 4.286s

I seems as It is not creating the permissions for the User, thanks in advance for you valuable help

You’re getting the permission object at:

But I don’t see where you’re assigning that permission to either the user or the group.

See Using the Django authentication system | Django documentation | Django

You´re right I’ll work on it and come back

Well, I change my code:

        user_group = Group.objects.get_or_create(name='Doctores')
        permission = Permission.objects.get(codename="add_paciente")
        user_group[0].permissions.add(permission)
        user_group[0].user_set.add(cls.user)

but it doesn’t still work :frowning:

Try with:

doctores = Group.objects.get_or_create(name='Doctores')
permission = Permission.objects.get(codename="add_paciente")
doctores.permissions.add(permission)
cls.user.groups.add(doctores)

Thanks for your answer. I already tried doing that but it doesn’t work :frowning:

Mistery solved: In the view, the value of permission_required should be “consultorio.add_paciente” instead of “can_add_paciente”. I made the changes and voila! it worked. PS: I got the answer with the help of Bing’s AI chat :open_mouth:

I have been used Bing Chat and GitHub Copilot and is an amazing way to improve your productivity.

2 Likes