简体   繁体   中英

AssertionError: 404 != 200 Failure in Django

I wrote test for all aspects of my model, but the very simple and basic one fails. Here is the urls.py

app_name = 'projects'
urlpatterns = [
    path('all/', ViewProjects.as_view(), name='all_projects'),
    path('project/<slug:project_slug>/',
         ProjectDetail.as_view(), name='project_detail'),
    path('new/', ProjectCreateView.as_view(), name='project_create'),
    path('', HomeView.as_view(), name='home'),
]

and its respective test:

class TestProject(TestCase):
    def test_project_list_view(self):
        url = reverse('projects:home')
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

This test gets failed, here is the traceback:

(Portfolio) PS D:\GitHub\Portfolio> python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.[2020-09-20 21:34:36,616] log: WARNING - Not Found: /
F
======================================================================
FAIL: test_project_list_view (projects.tests.TestProject)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\GitHub\Portfolio\projects\tests.py", line 11, in test_project_list_view
    self.assertEquals(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 2 tests in 0.113s

FAILED (failures=1)
Destroying test database for alias 'default'...

However, when I run python manage.py runserver the urls, views and template are all connected. What is the problem? Please help thank you.

edit:

class HomeView(ListView):
    model = Project
    template_name = 'index.html'
    context_object_name = 'projects'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['projects'] = Project.objects.all()
        react = get_object_or_404(Category, title='reactjs')
        context['react_projects'] = Project.objects.filter(
            category__title=react.title)
        django = get_object_or_404(Category, title='django')
        context['django_projects'] = Project.objects.filter(
            category__title=django.title)
        context['featured_blogs'] = Blog.objects.filter(featured=True)
        return context

IT seems that you do not have any fixtures in the test Database when you run tests. The method 'get_context_data' is used 'get_object_or_404' it seems that one of the classes mentioned does not have any instances so you run on this assertion error. Sometimes you can encounter this error when the reverse URL is set wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM