Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: int() argument must be a string or a number, not 'AnonymousUser' in Django

I've been testing my application and got stuck into error that does not seem to have anything to do with the application itself. I have a unit test like this:

class TagSaveAndLoadTest(TestCase):
    fixtures = ['users.json']

    def setUp(self):
        self.client = Client()
        self.client.login(user='test_user', password='123')

    def test_register_save(self):  
        tag_dict = {
                        'sex' : 4,
                        'drugs' : 3,
                        'rocknroll' : 1,
                    }
        response = self.client.post('/register/save_tags/', {'skilltags' : json.dumps(tag_dict)})
        self.assertEqual(response.status_code, 200)

The error I get is: TypeError: int() argument must be a string or a number, not 'AnonymousUser'. Files appearing in the traceback are base.py, manages.py, query.py, etc. It seems like my request gets stuck somewhere in the middleware, and I have no idea how to deal with it. How is it even possible for the request not to reach my view or even controller? Why there is a problem with AnonymousUser if the 'setUp()' function logs a test user in?

Full traceback can be found here, thanks in advance!

like image 713
martinthenext Avatar asked Feb 12 '12 23:02

martinthenext


2 Answers

Try not to be too intimidated by the traceback. The information you need is there, if you look up high enough past all the Django internals. The request is reaching your view, the problem isn't in the middleware. It looks like the client.login call is not working. The following filter statement fails because request.user is an an anonymous user

Skill.objects.filter(user=request.user).delete()

Try printing the client.login line in your test. It will return True if it successfully logs the user in. If that doesn't work, then check:

  1. You are using the correct username and password for your fixtures.
  2. You are loading the user fixtures successfully. Do you have the correct filename? The Django convention is user.json without an s.
  3. Make sure your test class subclasses the Django TestCase class so that the fixtures are loaded.
like image 129
Alasdair Avatar answered Oct 24 '22 18:10

Alasdair


The problem is in this line of code:

File "E:\ev\site\project\..\project\jobs\views.py", line 69, in post
  Skill.objects.filter(user=request.user).delete()

You're passing a user object as the value of a column condition in the ORM. Is this not your view?

like image 31
Ned Batchelder Avatar answered Oct 24 '22 18:10

Ned Batchelder