Django unit-testing for ProfileEditForm with disabled (read-only) fields

Viewed 135

I want to write unit tests for my ProfileEditForm form that has some fields with disabled=True. So, these fields are read-only and cannot be changed. I want to test this logic. As far as I know, I don't have to give disabled fields to the form. The form itself validates these fields.

models.py

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=63, blank=False)
    last_name = models.CharField(max_length=63, blank=False)
    about_me = models.CharField(max_length=511, blank=True)

forms.py

class ProfileEditForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = [
            "username",
            "email",
            "first_name",
            "last_name",
            "about_me",
        ]

    username = forms.CharField(label="Username", disabled=True)
    email = forms.EmailField(label="Email", disabled=True)
    first_name = forms.CharField(label="First Name", max_length=63, required=False)
    last_name = forms.CharField(label="Last Name", max_length=63, required=False)
    about_me = forms.CharField(label="About Me", max_length=511, required=False)

tests.py

class ProfileEditFormTests(TestCase):

    def setUp(self) -> None:
        self.user = get_user_model().objects.create_user(username="testuser",
                                                         email="test@test.com",
                                                         password="password123")
        self.profile = Profile.objects.create(user=self.user)

    def test_email_field_is_not_editable(self):

        form_data = {
            "username": self.profile.user.username,
            "email": self.profile.user.email,
            "first_name": "first",
            "last_name": "last",
            "about_me": "",
        }
        form = ProfileEditForm(data=form_data)
        self.assertTrue(form.is_valid())

I get:

AssertionError: False is not true

When I print out the form errors with print(form.errors):

<ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>email<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

Even if I provide all fields, the form is still invalid.

    form_data = {
        "username": self.profile.user.username,
        "email": self.profile.user.email,
        "first_name": "first",
        "last_name": "last",
        "about_me": "",
    }

I get the same error Nothing changes.

During the test, I check whether Profile instance is successfully created with Profile.objects.count(). The answer is yes.

To give you an idea: I'm using generic UpdateView for editing users' profiles with the help of ProfileEditForm. The view and form are working well.

How should I write unit tests for read-only fields?

0 Answers
Related