from django.test import TestCase
from cpf_field.forms import CPFFieldForm


class CPFFieldFormTestCase(TestCase):
    def test_form_has_field_cpf(self):
        """CPFFieldForm must have cpf field"""
        form = CPFFieldForm()
        self.assertEqual(['cpf'], list(form.fields))

    def test_cpf_has_invalid(self):
        """Values ​​that do not have 11 numbers or do not match a validating digit expression
        should return validation errors."""
        invalids = [
            ('12312312312', 'invalid'),
            ('123.123.123-12', 'invalid'),
            ('ABC12312312', 'invalid'),
            ('ABC.123.123-12', 'invalid'),
            ('12', 'invalid'),
            ('123456789012345', 'max_length'),
            ('123.123....-12', 'invalid'),
        ]
        for error, expected in invalids:
            with self.subTest():
                form = self.make_validated_form(cpf=expected)
                self.assertFormErrorCode(form, 'cpf', 'invalid')

    def test_cpf_valid(self):
        """Value that respect digits generator expression."""
        form = self.make_validated_form()
        self.assertTrue(form.is_valid())

    def assertFormErrorCode(self, form, field, code):
        """Auxiliary method for checking the error code of a given field."""
        errors = form.errors.as_data()[field][0]
        self.assertEqual(code, errors.code)

    def make_validated_form(self, **kwargs):
        """Build a valid form with **kwargs or a standard cpf.
        value generated by: https://www.4devs.com.br/gerador_de_cpf
        """
        valid = dict(cpf="293.856.080-02")
        data = dict(valid, **kwargs)
        form = CPFFieldForm(data)
        form.is_valid()
        return form
