-1

Hello I am brand new to unit testing and I just cant wrap my head around it. This is the simplest function I need to test and I am clueless as how to even do that. I know I need to pass a mock request object I think but beyond that I'm pretty lost. Could use some guidance.

def get_all_zones(request):
    user = request.user
    all_site = get_objects_for_user(user, 'sitehotspot_portal', klass=SiteHotspot).values_list('uid', 'name')
    all_site = [list(i) for i in all_site]
    all_area = get_objects_for_user(user, 'areashotspot_portal', klass=AreasHotspot).values_list('uid', 'name')
    all_area = [list(i) for i in all_area]
    all_sphere = get_objects_for_user(user, 'spherehotspot_portal', klass=SphereHotspot).values_list('uid', 'name')
    all_sphere = [list(i) for i in all_sphere]
    all_zones = all_area + all_site + all_sphere

    return(all_zones)```

2 Answers2

0

Is this method defined in a views.py file? Django provides a Client object, used to create and send requests to your views. This, in turn, simulates a user interacting with your application's views.

from django.test import Client

def test_get_all_zones(request):
   client = Client()
   response = client.get(reverse('your_app:get_all_zones_url'))

   # Test logic

Django has some pretty good documentation on it:

https://docs.djangoproject.com/en/3.0/intro/tutorial05/#the-django-test-client

Wassim Katbey
  • 298
  • 4
  • 9
0

You can use the RequestFactory to create an instance of a request and pass it to your view:

from django.test import RequestFactory

def test_get_all_zones():
    factory = RequestFactory()
    request = factory.get('/url/to/get_all_zones')
    response = get_all_zones(request)
    assert response.something

Please check the RequestFactory documentation for further details

bug
  • 3,900
  • 1
  • 13
  • 24