Search code examples
pythondjangodjango-modelsdjango-testing

Running Django tests.py on method that updates object


I'm using Django to try to run a test, and something's going wrong. Here's a minimal example:

models.py:

class Warrior(models.Model):
    is_alive = models.BooleanField("Is Alive?", default=True)
    def kill(self):
        self.alive = False
        self.save()

tests.py:

from django.test import TestCase
from .models import Warrior

class WarriorModelTests(TestCase):
    def test_kill(self):
        """kill() makes .alive False."""
        warrior = Warrior.objects.create()
        warrior.kill()
        self.assertIs(warrior.is_alive, False)

Any advice on this? I'm starting to think this little warrior chap is immortal. Thanks as always!


Solution

  • Since your kill() function sets alive to False, then you should assert the value of alive rather than is_alive, isn't it?

    You could print out the values to debug this.