Assert when an object could not be created in Django

1

I am testing the creation of an object and would like to know how to do the test to make an assert in case the object could not be created. For example:

   def test_expediente_sin_nombre(self):
    try:
        Expediente.objects.create(
            apellido_paterno='Prueba 2',
            apellido_materno='Prueba 1',
            estado_nacimiento='Oaxaca',
            fecha_nacimiento='2000-01-01'
        )
        self.fail("No se pudo crear")
    except FooException:
        pass
    expediente_counts = Expediente.objects.filter(apellido_paterno='Prueba 2').count()
    self.assertRaises(FooException)

In this case the file should not be created because the file is missing, if it is not created then the test passed.

    
asked by Esteban Quintana Cueto 24.04.2017 в 01:56
source

1 answer

1

I think you have two alternatives.

In production, you should capture that error when cleaning the data of a form, let's see the example of the documentation :

from django import forms

class ExpedienteForm(forms.Form):
    # ...

    def clean_nombre(self):
        data = self.cleaned_data['nombre']
        if "Esteban" not in data:
            raise forms.ValidationError("Falta el nombre!")
        return data

Or, you should indicate that the field is mandatory and validate in the model using Model.clean() , as indicated by the the same documentation :

class Expediente(models.Model):
    ...
    def clean(self):
        if self.nombre == None:
            raise ValidationError({'nombre': 'El nombre es obligatorio'})

And in the tests, verify that this error is launched:

def test_expediente_sin_nombre(self):
    expediente = Expediente.objects.create(
        apellido_paterno='Prueba 2',
        apellido_materno='Prueba 1',
        estado_nacimiento='Oaxaca',
        fecha_nacimiento='2000-01-01'
    )
    self.assertRaises(ValidationError, Expediente.clean)
    
answered by 24.04.2017 / 07:19
source