1 # -*- coding: utf-8 -*-
 
   2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
 
   3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   6 from django.core.files.base import ContentFile
 
   8 from catalogue.test_utils import (BookInfoStub, PersonStub, info_args,
 
   9         WLTestCase, get_fixture)
 
  10 from catalogue.models import Book
 
  11 from librarian import WLURI, XMLNamespace
 
  12 from search import Index, Search
 
  14 AtomNS = XMLNamespace("http://www.w3.org/2005/Atom")
 
  17 class OpdsSearchTests(WLTestCase):
 
  18     """Tests search feed in OPDS.."""
 
  20         WLTestCase.setUp(self)
 
  22         index.index.delete_all()
 
  25         with self.settings(NO_SEARCH_INDEX=False):
 
  26             self.do_doktora = Book.from_xml_file(
 
  27                 get_fixture('do-doktora.xml'))
 
  28             self.do_anusie = Book.from_xml_file(
 
  29                 get_fixture('fraszka-do-anusie.xml', catalogue))
 
  31     def assert_finds(self, query, books):
 
  32         """Takes a query and tests against books expected to be found."""
 
  33         tree = etree.fromstring(
 
  34             self.client.get('/opds/search/?%s' % query).content)
 
  35         elem_ids = tree.findall('.//%s/%s' % (AtomNS('entry'), AtomNS('id')))
 
  36         slugs = [WLURI(elem.text).slug for elem in elem_ids]
 
  37         self.assertEqual(set(slugs), set(b.slug for b in books),
 
  38             u"OPDS search '%s' failed." % query)
 
  40     def test_opds_search_simple(self):
 
  41         """Do a simple q= test, also emulate dumb OPDS clients."""
 
  42         both = set([self.do_doktora, self.do_anusie])
 
  43         self.assert_finds('q=fraszka', both)
 
  44         self.assert_finds('q=fraszka&author={opds:author}', both)
 
  46     def test_opds_search_title(self):
 
  47         """Search by title."""
 
  48         both = set([self.do_doktora, self.do_anusie])
 
  49         self.assert_finds('title=fraszka', both)
 
  50         self.assert_finds('title=fraszka', both)
 
  51         self.assert_finds('q=title:doktora', [self.do_doktora])
 
  53     def test_opds_search_author(self):
 
  54         """Search by author."""
 
  55         self.assert_finds('q=fraszka&author=Kochanowski', [self.do_doktora])
 
  56         self.assert_finds('q=fraszka+author:Kochanowski', [self.do_doktora])
 
  57         self.assert_finds('q=Kochanowski', [self.do_doktora])
 
  59     def test_opds_search_translator(self):
 
  60         """Search by translator."""
 
  61         self.assert_finds('q=fraszka&translator=Fikcyjny', [self.do_doktora])
 
  62         self.assert_finds('q=fraszka+translator:Fikcyjny', [self.do_doktora])
 
  63         self.assert_finds('q=Fikcyjny', [self.do_doktora])