Home > Software engineering >  Django TestCase check ValidationError with assertRaises in is throwing ValidationError
Django TestCase check ValidationError with assertRaises in is throwing ValidationError

Time:08-01

I have a model where i have overridden save function something like:

class MyModel(models.Model):
  number = models.PositiveIngeter()
  def save(self,*args, **kwargs)
    if self.number > 10:
      super().save(*args, **kwargs)
    else:
      raise ValidationError('msg')

and the function i am testing is like

def test_number(self):
  myModel = MyModel(number=5)
  self.assertRaises(ValidationError,myModel.save)

the error i got is like this:
ERROR: test_number(apps.players.tests.test_models.CityDetailTestCase)

Traceback (most recent call last):
  File "/home/sagar/project/apps/players/tests/test_models.py", line 740, in test_number
    self.asserttRaises(ValidationError,mumbai.save)
  File "/home/sagar/.pyenv/versions/3.5.9/lib/python3.5/unittest/case.py", line 733, in assertRaises
    return context.handle('assertRaises', args, kwargs)
  File "/home/sagar/.pyenv/versions/3.5.9/lib/python3.5/unittest/case.py", line 178, in handle
    callable_obj(*args, **kwargs)
  File "/home/sagar/.pyenv/versions/3.5.9/lib/python3.5/contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "/home/sagar/project/apps/players/models.py", line 2452, in save
    raise ValidationError("msg")
rest_framework.exceptions.ValidationError: ['msg']

I'm new to Django and unable to figure out what's wrong with this

CodePudding user response:

You don't need to call the method, simply pass it as a parameter:

from django.test import TestCase

class MyModelTest(TestCase):
   def test_my_model(self):
      myModel = MyModel(number=5)
      self.asserRaises(ValidationError, myModel.save)
  • Related