Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing - NoReverseMatch

Tags:

django

Why is this test does not work?

This is my views.py:

class ObjectDetailView(LoginRequiredMixin, DetailView):
    template_name = "object-detail.html"
    model = Object
    slug_field = 'username'

    def dispatch(self, request, *args, **kwargs):
        ....

urls.py:

url(r'^object/details/(?P<slug>[-\w.]+)/$', ObjectDetailView.as_view(), name='object-details'),

tests.py:

class ObjectViewsTestCase(TestCase):
    fixtures = ['/app/fixtures/object_fixture.json', ]

    def test_object_details(self):
        user = User.objects.get(id=1)
        self.client.login(username=user.username, password=user.password)
        resp = self.client.get(reverse('object-details', kwargs={'slug': user.username}))
        self.assertEqual(resp.status_code, 200)

My error:

NoReverseMatch: Reverse for 'object-details' with arguments '()' and keyword arguments '{'slug': u'admin'}' not found. 0 pattern(s) tried: []

like image 447
user3679444 Avatar asked May 27 '14 11:05

user3679444


People also ask

What does NoReverseMatch mean in Django?

NoReverseMatch (source code) is a Django exception that is raised when a URL cannot be matched against any string or regular express in your URL configuration. A URL matching problem is often caused by missing arguments or supplying too many arguments.

How do you solve NoReverseMatch?

Make sure you are passing the correct number of Arguments or Keyword arguments in URL template tag. As you can see in urls.py file, URL with name 'news-year-archive ' expects an argument 'year' in it. If you are not passing the year in url template tag, application will throw the error.

Is Django used for testing?

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behavior.


1 Answers

Do you have a ROOT_URLCONF in your settings ? If so, make sure that when you run the tests these settings are loaded. Or you can add the following in your tests :

class ObjectViewsTestCase(TestCase):
    fixtures = ['/app/fixtures/object_fixture.json', ]
    urls = 'path.to.your.urls'  # for instance 'base.app.urls'
like image 191
Seb D. Avatar answered Oct 13 '22 00:10

Seb D.