Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Test Case Can't run method

I am just getting started with Django, so this may be something stupid, but I am not even sure what to google at this point.

I have a method that looks like this:

def get_user(self,user):
    return Utilities.get_userprofile(user)

The method looks like this:

@staticmethod
def get_userprofile(user):
    return UserProfile.objects.filter(user_auth__username=user)[0]

When I include this in the view, everything is fine. When I write a test case to use any of the methods inside the Utility class, I get None back:

Two test cases:

def test_stack_overflow(self):
    a = ObjName()
    print(a.get_user('admin'))

def test_Utility(self):
    print(Utilities.get_user('admin'))

Results:

Creating test database for alias 'default'...
None
..None
.
----------------------------------------------------------------------

Can someone tell me why this is working in the view, but not working inside of the test case and does not generate any error messages?

Thanks

like image 624
nick_v1 Avatar asked Dec 20 '22 03:12

nick_v1


1 Answers

Verify whether your unit test comply the followings,

  1. TestClass must be written in a file name test*.py
  2. TestClass must have been subclassed from unittest.TestCase
  3. TestClass should have a setUp function to create objects(usually done in this way, but objects creation can happen in the test functions as well) in the database
  4. TestClass functions should start with test so as to be identified and run by the ./manage.py test command
  5. TestClass may have tearDown to properly end the unit test case.

Test Case Execution process:

When you run ./manage.py test django sets up a test_your_database_name and creates all the objects mentioned in the setUp function(Usually) and starts executing the test functions in the order of placement inside the class and once when all the test functions are executed, finally looks for the tearDown function executes if any present in the test class and destroys the test database.

It may be because that you might not have invoked objects creation in setUp function or elsewhere in the TestClass.

Can you kindly post the entire traceback and test file to help you better?

like image 167
Jagadesh Babu T Avatar answered Dec 24 '22 00:12

Jagadesh Babu T