Search code examples
djangodjango-formsdjango-tests

How to fetch a field class from a specific form in Django?


I'm trying to write a test for the username field and I want to use SimpleTestCase.assertFieldOutput(). The problem is that I cannot get the fieldclass from the field of my form:

import django
from django.test import TestCase

    class UserRegistrationTest(TestCase):
    """Tests for the user registration page."""

    def test_username_field(self):
        data = {'username': 'павел25',
                'password1': 'njkdpojv34',
                'password2': 'njkdpojv34',
                'email': '[email protected]',
                'first_name': 'Pavel',
                'last_name': 'Shlepnev'}
        f = RegistrationForm(data)
        self.assertFieldOutput(f.fields['username'], {'pavel25': 'pavel25'}, {'павел25': ['Имя пользователя должно содержать только символы ASCII.']})

When I run the test it raises TypeError: 'UsernameField' object is not callable


Solution

  • Wrapping in type() function seems to work. It gives me a class object which is what I need in the fieldclass argument in SimpleTestCase.assertFieldOutput().

    >>> type(f.fields['username'])
    <class 'django.contrib.auth.forms.UsernameField'>
    

    The test runs with no errors and produces valid output:

    import django
    from django.test import TestCase
    
    class UserRegistrationTest(TestCase):
    """Tests for the user registration page."""
    
        def test_username_field(self):
            data = {'username': 'павел25',
                    'password1': 'njkdpojv34',
                    'password2': 'njkdpojv34',
                    'email': '[email protected]',
                    'first_name': 'Pavel',
                    'last_name': 'Shlepnev'}
            f = RegistrationForm(data)
            self.assertFieldOutput(type(f.fields['username']), {'pavel25': 'pavel25'}, {'павел25': ['Имя пользователя должно содержать только символы ASCII.']})
    
        ======================================================================
        FAIL: test_username_field (accounts.tests.UserRegistrationTest)
        ----------------------------------------------------------------------
        Traceback (most recent call last):
          File "C:\Users\pavel\source\repos\Speak the Truth\accounts\tests.py", line 43, in test_username_field
            self.assertFieldOutput(type(f.fields['username']), {'pavel25': 'pavel25'}, {'павел25': ['Имя пользователя должно содержать только символы ASCII.']})
          File "C:\Users\pavel\source\repos\Speak the Truth\env\lib\site-packages\django\test\testcases.py", line 760, in assertFieldOutput
            required.clean(input)
        AssertionError: ValidationError not raised
    
        ----------------------------------------------------------------------