I'm having trouble logging in to test @login_required
views in my Django test cases.
我无法登录测试我的Django测试用例中的@login_required视图。
I have a CustomUser model that looks something like this:
我有一个CustomUser模型,看起来像这样:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', max_length=254, unique=True)
username = models.CharField('username', max_length=30, blank=True)
is_active = models.BooleanField('active', default=False, help_text='Designates whether this user should be treated as approved.')
objects = CustomUserManager()
USERNAME_FIELD = 'email'
Here's my test case:
这是我的测试用例:
class ViewTests(TestCase):
def test_create_user(self):
u = CustomUser.objects.create_superuser("u@u.ca","p")
u.is_active = True
u.save()
def test_add_project(self):
self.client.login(username="u@u.ca", password="p")
response = self.client.get(reverse('add-project'), {}, follow=True)
The user is created correctly and self.client.login()
works, but the response is just a redirect to my login page.
用户是正确创建的,self.client.login()可以正常工作,但响应只是重定向到我的登录页面。
I can create the user, log in correctly and use this view in a browser. How can I get the test client to do the same?
我可以创建用户,正确登录并在浏览器中使用此视图。如何让测试客户端也这样做?
1 个解决方案
#1
1
Each test method runs its own transaction which is rolled back at the end of the test. The data created in one test will not be available in another test. This login does not work because the user does not exist/was never created. If you need some common test data for your tests you can put that in the test case setUp
.
每个测试方法都运行自己的事务,该事务在测试结束时回滚。在一次测试中创建的数据在另一个测试中将不可用。此登录不起作用,因为用户不存在/从未创建过。如果您需要一些常用的测试数据,您可以将它放在测试用例setUp中。
#1
1
Each test method runs its own transaction which is rolled back at the end of the test. The data created in one test will not be available in another test. This login does not work because the user does not exist/was never created. If you need some common test data for your tests you can put that in the test case setUp
.
每个测试方法都运行自己的事务,该事务在测试结束时回滚。在一次测试中创建的数据在另一个测试中将不可用。此登录不起作用,因为用户不存在/从未创建过。如果您需要一些常用的测试数据,您可以将它放在测试用例setUp中。