django:用于过滤器查询搜索的测试用例开发

时间:2018-12-21 04:34:44

标签: django django-class-based-views django-tests

我正在测试Djngo Library应用程序,该应用程序具有Book模型和搜索栏以过滤那些书,用于检查title__icontains ='q'。

网址格式

path('search_book/', views.BookSearchListView.as_view(), name='search_book'),

网址路由:

 http://127.0.0.1:8000/catalog/search_book/?q=house

以下基于类的视图的实现:

class BookSearchListView(BookListView):
  paginate_by = 3

  def get_queryset(self):
    result = super(BookSearchListView, self).get_queryset()

    query = self.request.GET.get('q')
    if query:
        query_list = query.split()
        result = result.filter(
            reduce(operator.and_,
                   (Q(title__icontains=q) for q in query_list))
        )

    return result

在我的 tests.py 中,我必须为上述视图开发测试用例,但不知道如何进行测试。 我尝试了以下操作:

class BookSearchListViewTest(TestCase):
"""
        Test case for the Book Search List View
"""
   def setUp(self):
    test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK')
    test_user1.save()

    test_author = Author.objects.create(first_name='John', last_name='Smith')
    Book.objects.create(title='House', author=test_author, summary='Published in 1990',
                        isbn='123456789123')
    Book.objects.create(title='Money', author=test_author, summary='Published in 1991',
                        isbn='9876543210123')
    Book.objects.create(title='Mouse', author=test_author, summary='Published in 1992',
                        isbn='1293874657832')

   def test_redirect_if_not_logged_in(self):
    response = self.client.get(reverse('books'))
    self.assertRedirects(response, '/catalog/customer_login/?next=/catalog/books/')

   def test_query_search_filter(self):
    self.assertQuerysetEqual(Book.objects.filter(title__icontains='House'), ["<Book: House>"])

虽然test_query_search_filter测试成功运行,但是在我的覆盖率报告中,类BookSearchListView没有得到测试

我是Django中的一个新手,刚开始使用测试用例。 请帮忙!谢谢

2 个答案:

答案 0 :(得分:0)

您可以像这样测试它:

def test_redirect_if_not_logged_in(self):
    self.client.login(username='testuser1', password='1X<ISRUkw+tu')
    response = self.client.get(reverse('books'))
    self.assertQuerysetEqual(response.context['object_list'], Book.objects.all(), transform= lambda x:x)

您可以检查testing tools documentation以获得更多详细信息。

答案 1 :(得分:0)

如果您的网址中有参数,则应在测试用例中通过url发送。

您在Book方法中创建了一个标题为House的{​​{1}}对象;

setUp