简体   繁体   中英

How to test a Queryset in Django

I'm quite new to Django and need help with testing my view module. Right now the view only returns all the objects from the DB:

def get_queryset(self):
    return people.objects.all()

I want to test that the view returns all the objects. I know that I should use assertQuerysetEqual and I have read about it but still not sure how to implement it because I couldn't understand much from the documentation. Would appreciate it greatly if someone could show some examples or explain.

Considering you are using class-based views. You can do the following steps to test get_queryset method. Process for testing other functions should be similer.

  1. Create a request object using request factory from django.

from django.test import RequestFactory


request = RequestFactory().get('/view-path')
  1. Create a view instance

view = YourView()
  1. Attach request to view

view.request = request
  1. Call your method and compare results.

qs = view.get_queryset()

Whole test-case would look something like this

def test_get_queryset(self):
    request = RequestFactory().get('/view-path')
    view = YourView()
    view.request = request

    qs = view.get_queryset()

    self.assertQuerysetEqual(qs, people.objects.all())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM