这个问题在这里已有答案:
我想测试Urls是否收到500错误。在不需要登录的正常情况下,我得到status_code 200但是在需要登录的地方,它给出了302错误。那么,如何以最佳方式测试登录需求和参数化URL。
谢谢
所以我添加这个是因为有人把这个问题链接成了重复但是这不是我的答案,为什么它不是我的答案,因为我可以使用这种方法登录但是我想测试那个视图已经登录的网址我可以登录但不能登录那个观点
c.post('login/', {
'username': 'nitin',
'password': 'qwerty123321'})
如果你不知道url的答案,那么在那个问题上的'views'How to test views with pytest whose views has LoginRequired and some specific user dependencies结账问题我得到用户使用mixer.blend()登录,这很好但是在'views'中用户有更多与此相关的功能只检查一次。请帮助我,谢谢你。
至少告诉我该怎么办呢我对此很不满意。再次感谢你
path('', event_views.dashboard_view, name='event-dashboard'),
@login_required
def dashboard_view(request):
# ccd = Org.objects.first()
# print(ccd.__dict__)
# print(request.user.)
org = request.user.profile.org
week_responses = day_wise_responses(7, org)
user_org = request.user.profile.org.name
sms_sent = org.sms_counter
email_sent = org.email_counter
today = datetime.today().date()
responses_one_week = number_of_responses(7, org)
responses_two_week = number_of_responses(14, org)
average_rating = org_average_rating(org)
responses_last_week = responses_two_week - responses_one_week
if responses_last_week:
responses_percent_change = (abs(responses_one_week - responses_last_week)/responses_last_week)*100
else:
responses_percent_change = responses_one_week*100
# last n responses
last_5_responses = last_n_responses(5, org)
# print(last_5_responses)
context = {'week_responses': week_responses, 'user_org': user_org, 'today': today,
'responses_one_week': responses_one_week, 'responses_percent_change': responses_percent_change,
'last_5_responses': last_5_responses, 'sms_sent': sms_sent, 'email_sent': email_sent,
'average_rating': average_rating}
return render(request, 'events/dashboard.html', context)
@pytest.mark.django_db
class TestUrls(test.TestCase):
def test_event_dashboard(self):
c = Client()
c.post('login/', {
'username': 'nitin',
'password': 'qwerty123321'})
response = c.get(reverse('event-dashboard'))
self.assertEqual(response.status_code, 200)
302是因为您的用户被重定向到登录屏幕。
如果要测试需要身份验证的视图,则需要首先对用户进行身份验证。
幸运的是,这很容易做到。见docs。
# Create a new user
User.objects.create_user(
username='fred',
password='secret'
)
# Start up a test client
c = Client()
# Authenticate the user on the client
c.login(username='fred', password='secret')
# Do your thing
response = c.get(reverse('event-dashboard'))
self.assertEqual(response.status_code, 200)