AssertionError: 302 != 200

2020-04-26 04:02发布

I tried to create a test in my tests.py

class TaskViewTests(TestCase):
    def test_task_view_with_no_task(self):
        """
        If no task exist, an appropriate message should be displayed.
        """
        userName = 'esutek'
        response = self.client.get(reverse('actuser:task',args=(userName,)))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No task are available.")
        self.assertQuerysetEqual(response.context['taskList'], [])

However it gives me this error message. I don't have any clue why this happened. I just followed the tutorial.

actuser:task views.py

def task(request, userName):
    """ User task list in actInbox
    """

    user = ActuserViewModel()
    user.get_task_list(userName)

    return render(request, 'actuser/task.html', {
                'userName': userName,
                'taskList': user.taskList,
                'dateToday': user.dateToday,
           })

viewmodels.py

def get_task_list(self, userName):
    self.taskList = Task.objects.filter(executor = userName, parent_task_id=EMPTY_UUID).order_by('due_date')
    #get date now with this format 05/11
    self.dateToday = datetime.date.today()

Actually I got 2 urls...

this is from the project

url(r'^(?P<userName>[0-9a-zA-Z--]+)/', include('actuser.urls', namespace="actuser")),

and this one is from actuser.urls

url(r'^task/$', views.task, name='task'),

2条回答
成全新的幸福
2楼-- · 2020-04-26 04:29

HTTP 302 means that you are redirected to some other URL. You can do a redirect intentionally if you use a RedirectView for example, or accidentally if you forget to write slash at the end of the request URL and you have APPEND_SLASH enabled (in that case, you get HTTP 301 instead of 302).

You need a slash at the end:

url(r'^(?P<userName>[0-9a-zA-Z-]+)/task/$', ...
查看更多
Root(大扎)
3楼-- · 2020-04-26 04:30

You could be getting a redirect if your view requires login.

You need to login first, this is a good example of how to do it: Django: test failing on a view with @login_required

Briefly:

class LoginTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

    def testLogin(self):
        self.client.login(username='john', password='johnpassword')
        response = self.client.get(reverse('testlogin-view'))
        self.assertEqual(response.status_code, 200)
查看更多
登录 后发表回答