-
Notifications
You must be signed in to change notification settings - Fork 2
Unit testing Urls
First step is to create a test folder in the app we are about to run the test.
In out case we will create a test folder in bus app. For django to run these tests automatically we need to make this folder into a package. Therefore add the __init__.py
. After that create a file with a name starting with test
so that django can automatically find and run them using the command
python manage.py test app_name
So here we will test urls. By testing Urls we check to see if all the views associated with the URLs are correct or not.
We will use two functions to achieve this resolve
and reverse
.
if we go back to our app and look at urls.py
urlpatterns = [
path('',views.home,name="home"),
path('tourism/', views.tourism, name="tourism"),
path('prediction/', views.prediction, name="prediction"),
path('share/<start_lat>/<start_lng>/<stop_lat>/<stop_lng>/<start>/<stop>/', views.share, name="share"),
path('add_fav_destination/', views.addFavDest, name="addFavDest"),
path('delete_fav_destination/', views.delFavDest, name="delFavDest"),
]
We see that each url is associated with a view and has a name.
The reverse
function takes name of url and reverses it to give the Url of the view associated with it.
The resolve
function gets all properties associated with url including the views associated therefore using these two we can do unit test.
from django.test import SimpleTestCase
from django.urls import reverse, resolve
# the import below just imports the view here we check the function home
from bus.views import home
class TestUrls(SimpleTestCase):
"""Class used for testing URLS"""
def test_home_url_resolved(self):
url = reverse("home")
print(url)
print(resolve(url))
self.assertEqual(resolve(url).func, home)
If we resolved as per assertion when we run the test we should get ok status
- Django installation
- Django Project creation
- Package Directories
- Hello,World
- Setting up projects
- Routing
- Templating
- Django templating Engine syntax
- Passing variable to template
- Template inheritance
- Static file linking
- Admin page
- Django ORM
- Making DB
- ORM based queries
- Django Model set
- Use of ORM DB with Django