Home > database >  Why does my Django test pass when it should fail?
Why does my Django test pass when it should fail?

Time:07-31

I am new to testing of any sorts in coding. This is followup on this answer to my question. Answer establishes that this type of model method should not save object to database:

@classmethod
def create(cls, user, name):
    list = cls(user=user, name=name) 
    return list

If this is the case I am curious why does this test pass and says everything is ok?

from django.test import TestCase
from .models import List
from django.contrib.auth.models import User

class ListTestCase(TestCase):
    def setUp(self):
        user_1 = User(username="test_user", password="abcd")
        user_1.save()
        List.objects.create(user=user_1, name="mylist")
        List.objects.create(user=user_1, name="anotherlist")
        
    def test_lists_is_created(self):
        user_1 = User.objects.get(username="test_user")
        list_1 = List.objects.get(user=user_1, name="mylist")
        self.assertEqual("mylist", list_1.name)
   

CodePudding user response:

The reason why the test passes is that you call a different method from the one that you've implemented.

The line in ListTestCase.setUp()

List.objects.create(user=user_1, name="mylist")

actually, call the Django's QuerySet.create() method. Notice that it's call via List.objects.create() not List.create(). Therefore, the object is saved in the database and the test passes.

In your case, you've implemented a method create() inside the List model, so you should call List.create().

  • Related