1. Bruce Kroeze
  2. django-threaded-multihost
  3. Issues
Issue #8 resolved

get_current_user is broken when testing

Ryan Kaskel
created an issue

We use threaded_multihost's EditorField and CreatorField in our project and during testing I came across some strange behavior.

Consider the following test cases (this can be copy and pasted into threaded_multihost.test_app.model_tests.tests or see the attached diff):


from django.test import TestCase

class SomeTests(TestCase): def test_some_test(self): foo_user = User.objects.create(username="foo") set_current_user(foo_user)

class TestStaleUser(TestCase): def test_deleted_user(self): self.assertEqual(get_current_user().username, "foo") self.assertEqual(User.objects.count(), 0)

    article = ArticleCreator.objects.create(text="text")
    self.assertRaises(User.DoesNotExist, getattr, article, 'user')

    bar_user = User.objects.create(username="bar")

    self.assertEqual(ArticleCreator.objects.count(), 1)


In the first test case, "SomeTests," we set the thread's local user to a User object with the username of "foo" to simulate what would happen if "foo" was logged in and made a request.

In the next test case, "TestStaleUser," which we would assume to be totally isolated from the first test case, get_current_users returns a "stale" user object with pk=1 and username="foo". This can't be what we want because that user was created in a different test case and doesn't exist now.

The side effects of this are demonstrated next. First, if you try to access the CreatorField on the model (named "user"), a DoesNotExist exception is raised because obviously a user with pk=1 does not exist in this test case: get_current_user as used in the project return stale data.

Worse still, if you create a new user, "bar", which naturally has pk=1, and then delete the user right away, the ArticleCreator object will also be deleted because of the cascade even though there is no logical connection between bar_user and the ArticleCreator object.

This only happens when you use Django's TestCase (tested with versions 1.2.5 and 1.3) and not when you use unittest.TestCase like all the other tests in threaded_multihost use (because the test database is destroyed between tests). I don't know if this can be fixed.

I've attached a diff and here is the command I ran to test the issue (the tests need to run in this order):

python manage.py test model_tests.SomeTests model_tests.TestStaleUser

Comments (4)

  1. Log in to comment