我正在为要求用户登录的视图编写测试。我想编写一个装饰器,以向每个测试中添加一个登录用户。
例如,而不是写:
def test_view_url(cls):
get_user_model().objects.create_user(username='Paulian', password='yGy2pl12')
cls.client.login(username='Paulian', password='yGy2pl12')
response = cls.client.get(cls.home_view_url)
cls.assertEqual(200, response.status_code)
我要写:
@user_is_logged_in
def test_view_url(cls):
response = cls.client.get(cls.home_view_url)
cls.assertEqual(200, response.status_code)
这是我当前和有缺陷的装饰器:
def user_is_logged_in(func) -> object:
def wrapper(func):
c = Client()
if c.login(username='Paulian', password='yGy2pl12'):
pass
else:
get_user_model().objects.create_user(username='Paulian', password='yGy2pl12')
c.login(username='Paulian', password='yGy2pl12')
return wrapper
return wrapper