I have a Participant
model that contains a django.contrib.auth.model.User
with it's is_active
property to False
. That prevents these users from logging themselves in. An admin user has to do that for them, using some custom code I've written that uses django.contrib.auth.authenticate()
.
I need to be able to authenticate these users in my tests,
class ParticipantFactory(factory.django.DjangoModelFactory):
class Meta:
model = Participant
user = factory.SubFactory(InactiveUserFactory)
first_location = factory.SubFactory(LocationFactory)
location = factory.SubFactory(LocationFactory)
study_id = FuzzyText(prefix='7')
class BasicTest(TestCase):
def setUp(self):
self.u = User.objects.create_user(
'test_user', '[email protected]', 'test_pass')
self.u.is_active = False
self.u.save()
self.participant = ParticipantFactory(user=self.u)
# This works but has no effect on the tests
auth = authenticate(username=self.u.username, password='test_pass')
assert(auth is not None)
# This fails because the user is inactive
# login = self.client.login(username=self.u.username,
# password='test_pass')
# assert(login is True)
Does anyone have an idea how to authenticate this inactive user?
I was able to solve this by setting the user to active right before doing the login:
class BasicTest(TestCase):
def setUp(self):
u = InactiveUserFactory()
u.set_password('test_pass')
u.save()
self.participant = ParticipantFactory(user=u)
self.u = self.participant.user
self.u.is_active = True
self.u.save()
login = self.client.login(username=self.u.username,
password='test_pass')
assert(login is True)
self.u.is_active = False
self.u.save()