Home > front end >  django pytest how to test a view with argument(id)
django pytest how to test a view with argument(id)

Time:02-23

i have a question regarding using pytest. These are my very 1st tests. I have 2 views which i want to test (simplest possible way).

Views:

class MenuView(View):
    def get(self, request):
        return render(request, 'diet_app/menu.html')

class CuisineDetailsView(View):
    def get(self, request, id):
        cuisine = Cuisine.objects.get(id=id)
        recipes = cuisine.recipe_set.all()
        return render(request, 'diet_app/cuisine_details.html', {'cuisine': cuisine, 'recipes': recipes})

Here are my tests:

def test_menu(client):
    url = reverse('menu')
    response = client.get(url)
    assert response.status_code == 200

@pytest.mark.django_db
def test_cuisine_details_view(client):
    url = reverse('cuisine-details')
    response = client.get(url)
    assert response.status_code == 200

Urls:

path('menu/', MenuView.as_view(), name='menu'),
path('cuisine_details/<int:id>/', CuisineDetailsView.as_view(), name='cuisine-details'),

1st test (menu view) is working properly

2nd test (cuisine details view) shows error

.NoReverseMatch: Reverse for 'cuisine-details' with no arguments not found. 1 pattern(s) tried: ['cuisine_details\\/(?P<id>

I know i should probably put somethere ID argument but tried few options and havent succeed. Will be grateful for any help/advise

CodePudding user response:

You must pass the id as argument to the reverse function.

@pytest.mark.django_db
def test_cuisine_details_view(client):
    url = reverse('cuisine-details', kwargs={'id': 123})
    response = client.get(url)
    assert response.status_code == 200
  • Related