vendredi 4 octobre 2019

how to test django get_absolute_url with unittest

I am trying to test get_absolute_url with unittest but i keep failing to pass the test.

Any thought on how to test it properly?

models.py

class Address(models.Model):
    venue = models.CharField(max_length=1000)
    longitude = models.CharField(max_length=1000)
    latitude = models.CharField(max_length=1000)
    postal_code = models.IntegerField()
    person = models.ForeignKey(User, on_delete=models.CASCADE, related_name='person_addresses')

    def __str__(self):
        return self.venue

    def get_absolute_url(self):
        return reverse('core:address_detail', kwargs={'pk': self.pk })

urls.py

from django.contrib import admin
from django.urls import path, include
from . import views

app_name = 'core'
urlpatterns = [
    path('', views.address_list, name='address_list'),  
    path('<int:id>/', views.address_detail, name='address_detail'),
]

test_models.py

from django.test import TestCase
from core.models import Address
from django.contrib.auth import get_user_model
from django.urls import reverse

User = get_user_model()

class AddressModelTest(TestCase):
    def setUp(self):
        self.user = User.objects.create(username='amanda', password='amanda')

        self.address = Address.objects.create(
                    venue="901 S Miami Ave, Miami, FL", 
                    person=self.user,
                    longitude="-80.193039",
                    latitude="25.765051",
                    postal_code="33130",
        )


    def test_address_get_absolute_url(self):
        # I tried 'self.client.post' and 'self.client.get' below, both are not working.
        response = self.client.post(reverse('core:address_detail', kwargs={'pk':self.address.pk}))   
        self.assertEqual(response, self.address.pk)

error from console

django.urls.exceptions.NoReverseMatch: Reverse for 'address_detail' with keyword arguments '{'pk': 4}' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$']

Any help would be much appreciate.

Aucun commentaire:

Enregistrer un commentaire