예제 #1
0
    def test_book_adder_blank_person(self):
        self.make_current_user()
        isbn = fake.isbn()

        # Check that the relevant records do not exist yet
        self.verify_does_not_exist(Book, isbn=isbn)
        self.verify_does_not_exist(Genre, name="io9")
        self.verify_does_not_exist(BookCompany, name="Scholastic")
        self.verify_does_not_exist(BookCompany, name="UP Press")
        author = [Person(lastname="", firstname="")]

        single_author = BookRecord(isbn=isbn,
                                   title="The Carpet Makers",
                                   genre="io9",
                                   author=author,
                                   publisher="Scholastic",
                                   printer="UP Press",
                                   publish_year=2013)

        single_rv = self.client.post("/api/add/books",
                                     data=single_author.request_data())

        self.assertEquals(single_rv._status_code, 400)

        self.verify_does_not_exist(Book, isbn=isbn)
        self.verify_does_not_exist(Genre, name="io9")
        self.verify_does_not_exist(BookCompany, name="Scholastic")
        self.verify_does_not_exist(BookCompany, name="UP Press")
예제 #2
0
    def test_get_books(self):
        self.app.logger.setLevel(logging.INFO)
        roles = librarian.db.session.query(Role).all()
        all_db_books = librarian.db.session.query(Book).all()
        self.assertEquals(0, len(all_db_books))
        book_count = 12

        library = create_library(librarian.db.session,
                                 self.admin_user,
                                 roles,
                                 book_person_c=12,
                                 company_c=8,
                                 book_c=book_count,
                                 participant_c=32)

        all_db_books = librarian.db.session.query(Book).all()
        self.assertEquals(book_count, len(all_db_books))

        get_books = self.client.get("/api/read/books?limit=%s" % book_count)
        self.assertEquals(200, get_books._status_code)
        ret_data = json.loads(get_books.data)["data"]
        return_set = set()
        # This is solely for debugging only. Remove eventually!
        return_list = []

        for book in ret_data:
            return_set.add(BookRecord.make_hashable(book))
            return_list.append(BookRecord.make_hashable(book))

        self.app.logger.info("Everything returned: %s" % str(return_list))
        self.assertEquals(book_count, len(return_set))
        self.assertEquals(set(library), return_set)
예제 #3
0
def search(searchq):
    # Will only fail if some f*cker names their book after their own ISBN.
    results = BookRecord.base_assembler_query()
    if ISBN_REGEX.match(searchq):
        alt_isbn = make_equivalent_isbn(searchq)
        results = results.filter(
            or_(Book.isbn == searchq, Book.isbn == alt_isbn)).all()
    else:
        contrib_query = (db.session.query(
            Book.id).filter(BookContribution.book_id == Book.id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    func.concat(Contributor.firstname, ' ',
                                Contributor.lastname).ilike("".join(
                                    ("%", searchq, "%")))).all())
        contribooks = [bid for bid, in contrib_query]
        results = (BookRecord.base_assembler_query().filter(
            or_(
                Book.title.ilike("".join(("%", searchq, "%"))),
                and_(Book.publisher_id == BookCompany.id,
                     BookCompany.name.ilike("".join(("%", searchq, "%")))),
                Book.id.in_(contribooks) if contribooks else False)).all())

    book_listing = BookRecord.assembler(results, as_obj=False)

    return book_listing
예제 #4
0
    def test_title_edit_book(self):
        self.make_current_user()
        authors = [ContributorFactory().make_plain_person() for _ in range(3)]
        book = BookRecord(isbn=fake.isbn(),
                          title=fake.title(),
                          publisher="Mumford and Sons",
                          author=authors,
                          publish_year=2016,
                          genre="Fiction")
        book_id = create_book(librarian.db.session, book, self.admin_user)
        librarian.db.session.commit()

        existing = (librarian.db.session.query(Book).filter(
            Book.isbn == book.isbn).first())
        self.assertEquals(book.title, existing.title)

        edit_data = BookRecord(isbn=book.isbn,
                               title="This is a Ret Con",
                               publisher=book.publisher,
                               author=book.authors,
                               publish_year=book.publish_year,
                               genre=book.genre,
                               id=book_id)
        edit_book = self.client.post("/api/edit/books",
                                     data=edit_data.request_data())
        self.assertEqual(200, edit_book.status_code)

        edited = (librarian.db.session.query(Book).filter(
            Book.isbn == book.isbn).first())
        self.assertEquals(edit_data.title, edited.title)
예제 #5
0
    def test_repeat_people(self):
        """
        Test that API call should still succeed even if the people have been
        added before.
        """
        def insert_bookpersons(persons):
            for p in persons:
                bp = Contributor(firstname=p.firstname,
                                 lastname=p.lastname,
                                 creator=self.admin_user)
                librarian.db.session.add(bp)

            librarian.db.session.flush()

        def verify_bookperson(p):
            self.verify_inserted(Contributor,
                                 firstname=p.firstname,
                                 lastname=p.lastname)

        self.make_current_user()
        isbn = fake.isbn()
        title = fake.title()

        authors = [make_person_object() for _ in range(4)]
        insert_bookpersons(authors)
        map(verify_bookperson, authors)

        illustrators = [make_person_object() for _ in range(4)]
        insert_bookpersons(illustrators)
        map(verify_bookperson, illustrators)

        editors = [make_person_object() for _ in range(4)]
        insert_bookpersons(editors)
        map(verify_bookperson, editors)

        translators = [make_person_object() for _ in range(4)]
        insert_bookpersons(translators)
        map(verify_bookperson, translators)

        req_data = BookRecord(isbn=isbn,
                              title=title,
                              genre="Multinational",
                              author=authors,
                              illustrator=illustrators,
                              editor=editors,
                              translator=translators,
                              publisher="Scholastic",
                              printer="UP Press",
                              publish_year=2013)

        req_val = self.client.post("/api/add/books",
                                   data=req_data.request_data())
        self.assertEqual(200, req_val.status_code)
예제 #6
0
    def test_book_adder_duplicate_isbn10(self):
        """
        Switch ISBNs of test_book_adder_duplicate_isbn13.
        """
        self.make_current_user()
        isbn13 = "1596914696"

        self.verify_does_not_exist(Book, isbn=isbn13)
        self.verify_does_not_exist(Genre, name="Academic Nonfiction")
        self.verify_does_not_exist(Contributor,
                                   lastname="Bayard",
                                   firstname="Pierre")
        self.verify_does_not_exist(Contributor,
                                   lastname="Mehlman",
                                   firstname="Jeffrey")
        self.verify_does_not_exist(BookCompany, name="Bloomsbury")
        self.verify_does_not_exist(BookCompany,
                                   name="Quebecor World Fairfield")

        author = [Person(lastname="Bayard", firstname="Pierre")]
        translator = [Person(lastname="Mehlman", firstname="Jeffrey")]
        books_you_havent_read = BookRecord(
            isbn=isbn13,
            title="How to Talk About Books You Haven't Read",
            author=author,
            translator=translator,
            genre="Academic Nonfiction",
            publisher="Bloomsbury",
            printer="Quebecor World Fairfield",
            publish_year=2007)

        havent_read_rv = self.client.post(
            "/api/add/books", data=books_you_havent_read.request_data())

        self.verify_inserted(Book, isbn=isbn13)
        self.verify_inserted(Genre, name="Academic Nonfiction")
        self.verify_inserted(Contributor,
                             lastname="Bayard",
                             firstname="Pierre")
        self.verify_inserted(Contributor,
                             lastname="Mehlman",
                             firstname="Jeffrey")
        self.verify_inserted(BookCompany, name="Bloomsbury")
        self.verify_inserted(BookCompany, name="Quebecor World Fairfield")

        books_you_havent_read.isbn = "9781596914698"

        duplicate = self.client.post("/api/add/books",
                                     data=books_you_havent_read.request_data())

        self.assertEquals(duplicate._status_code, 409)
예제 #7
0
    def test_edit_book_contrib_add(self):
        self.make_current_user()
        authors = [ContributorFactory().make_plain_person() for _ in range(3)]
        book = BookRecord(isbn=fake.isbn(),
                          title=fake.title(),
                          publisher="Mumford and Sons",
                          author=authors,
                          publish_year=2016,
                          genre="Fiction")
        book_id = create_book(librarian.db.session, book, self.admin_user)
        librarian.db.session.commit()

        author_role = Role.get_preset_role("Author")
        book_authors = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == author_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        author_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in book_authors
        ])
        self.assertEquals(set(authors), author_persons)

        additional_author = ContributorFactory().make_plain_person()
        _book_authors = copy.deepcopy(list(book.authors))
        _book_authors.append(additional_author)
        edit_data = BookRecord(isbn=book.isbn,
                               title=book.title,
                               publisher=book.publisher,
                               author=_book_authors,
                               publish_year=book.publish_year,
                               genre=book.genre,
                               id=book_id)
        librarian.db.session.commit()
        edit_book = self.client.post("/api/edit/books",
                                     data=edit_data.request_data())
        self.assertEqual(200, edit_book.status_code)

        book_authors = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == author_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        author_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in book_authors
        ])
        self.assertEqual(set(_book_authors), author_persons)
예제 #8
0
    def test_no_printer(self):
        self.make_current_user()
        single_author = BookRecord(
            isbn="9780062330260",
            title="Trigger Warning",
            genre="Short Story Collection",
            author=[Person(lastname="Gaiman", firstname="Neil")],
            publisher="William Morrow",
            publish_year=2015)

        single_rv = self.client.post("/api/add/books",
                                     data=single_author.request_data())

        self.assertEquals(single_rv._status_code, 200)
예제 #9
0
    def __basic_edit_test(self, book_id):
        author_role = Role.get_preset_role("Author")
        book = (librarian.db.session.query(Book).filter(
            Book.id == book_id).first())
        book_authors = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == author_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        authors = [co.make_plain_person() for co in book_authors]
        the_deleted = book_authors[-1]
        author_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in book_authors
        ])

        edited_book_authors = authors[0:-1]
        edit_data = BookRecord(isbn=book.isbn,
                               title=book.title,
                               publisher=book.publisher,
                               author=edited_book_authors,
                               publish_year=book.publish_year,
                               genre=book.genre.name,
                               id=book_id)
        edit_book = self.client.post("/api/edit/books",
                                     data=edit_data.request_data())
        self.assertEqual(200, edit_book.status_code)
        updated_book_authors = (
            librarian.db.session.query(Contributor).filter(
                BookContribution.book_id == book_id).filter(
                    BookContribution.contributor_id == Contributor.id).filter(
                        BookContribution.role_id == author_role.id).filter(
                            BookContribution.active)
            # Just for thoroughness, but in an ideal world BookContribution.active is sufficient
            .filter(Contributor.active).all())
        updated_author_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in updated_book_authors
        ])
        self.assertEqual(set(edited_book_authors), updated_author_persons)
        # Verify that the BookRecord for the "deleted" contribution remains
        # but inactive.
        self.verify_inserted(BookContribution,
                             book_id=book_id,
                             contributor_id=the_deleted.id,
                             role_id=author_role.id,
                             active=False)
        self.verify_inserted(Contributor, id=the_deleted.id, active=False)
예제 #10
0
    def test_get_books_offset(self):
        self.app.logger.setLevel(logging.INFO)
        roles = librarian.db.session.query(Role).all()
        all_db_books = librarian.db.session.query(Book).all()
        self.assertEquals(0, len(all_db_books))
        book_count = 12
        limit = 8

        library = create_library(librarian.db.session,
                                 self.admin_user,
                                 roles,
                                 book_person_c=12,
                                 company_c=8,
                                 book_c=book_count,
                                 participant_c=32)

        all_db_books = librarian.db.session.query(Book).all()
        self.assertEquals(book_count, len(all_db_books))

        offset = 0
        return_set = set()
        max_iters = int(math.ceil(book_count / limit))

        while len(return_set) < book_count and offset < max_iters:
            get_books = self.client.get("/api/read/books?offset=%s" % offset)
            self.assertEquals(200, get_books._status_code)
            ret_data = json.loads(get_books.data)["data"]

            for book in ret_data:
                return_set.add(BookRecord.make_hashable(book))

            offset += 1

        self.assertEquals(len(return_set), book_count)
        self.assertEquals(set(library), return_set)
예제 #11
0
    def test_create_book(self):
        sample_isbn = "9780306406157"
        # ensure it does not exist
        bookq = librarian.db.session.query(Book).filter(
            Book.isbn == sample_isbn)
        book = bookq.first()

        self.assertTrue(book is None)
        br = BookRecord(isbn=sample_isbn,
                        title="Another Chance for Poland",
                        publisher="Eurosport",
                        author=(Person(lastname="Enrique",
                                       firstname="Luis"), ),
                        publish_year=2016,
                        id=314,
                        genre="Test")
        utils.create_book(librarian.db.session, br, self.admin_user)

        book = bookq.first()
        self.assertTrue(book is not None)

        # Ensure that it has contributors
        contribs = (librarian.db.session.query(BookContribution).filter(
            BookContribution.book_id == book.id).all())

        self.assertTrue(len(contribs) > 0)
예제 #12
0
    def test_multiple_same_names(self):
        self.make_current_user()
        Neil_Gaiman = Person(lastname="Gaiman", firstname="Neil")
        single_author = BookRecord(isbn="9780062330260",
                                   title="Trigger Warning",
                                   genre="Short Story Collection",
                                   author=[Neil_Gaiman, Neil_Gaiman],
                                   publisher="William Morrow",
                                   publish_year=2015)
        single_rv = self.client.post("/api/add/books",
                                     data=single_author.request_data())

        self.assertEquals(200, single_rv.status_code)

        gaimen = (librarian.db.session.query(Contributor).filter(
            Contributor.firstname == 'Neil').filter(
                Contributor.lastname == 'Gaiman').all())

        self.assertEquals(1, len(gaimen))
예제 #13
0
    def test_edit_books(self):
        self.set_current_user(self.admin_user)

        authors = [ContributorFactory().make_plain_person()]
        book = BookRecord(isbn=fake.isbn(), title=fake.title(), publisher="p",
          author=authors, publish_year=2016, genre="Fiction")
        book_id = create_book(librarian.db.session, book, self.admin_user)
        librarian.db.session.commit()

        visit = self.client.get("/books/edit?bid=%d" % book_id)
        self.assertEqual(200, visit.status_code)
예제 #14
0
 def __make_book(self):
     contributor_objs = [ContributorFactory() for _ in range(3)]
     authors = [co.make_plain_person() for co in contributor_objs]
     book = BookRecord(isbn=fake.isbn(),
                       title=fake.title(),
                       publisher="somepublisher",
                       author=authors,
                       publish_year=2017,
                       genre="Fiction")
     book_id = create_book(librarian.db.session, book, self.admin_user)
     librarian.db.session.commit()
     return book_id
예제 #15
0
    def test_extra_whitespace(self):
        self.make_current_user()
        self.verify_does_not_exist(Contributor,
                                   lastname="de Cervantes",
                                   firstname="Miguel")

        spaced = BookRecord(
            isbn="0812972104",
            title="Don Quixote",
            genre="Fiction",
            author=[Person(lastname="  de Cervantes  ", firstname="Miguel")],
            publisher="Modern Library",
            publish_year=2006)

        spaced_rv = self.client.post("/api/add/books",
                                     data=spaced.request_data())
        self.assertEquals(200, spaced_rv.status_code)

        self.verify_inserted(Contributor,
                             lastname="de Cervantes",
                             firstname="Miguel")
예제 #16
0
 def test_search_publisher(self):
     search_book = BookRecord(isbn=fake.isbn(),
                              title="Totally Unrelated to Search Query",
                              publisher="Walnut Publishing",
                              publish_year=2017,
                              author=[Person("Hawking", "Stevie")],
                              genre="Test")
     create_book(librarian.db.session, search_book, self.admin_user)
     librarian.db.session.flush()
     results = api.search("walnut")
     self.assertEqual(len(results), 1)
     self.assertEqual(results[0]["isbn"], search_book.isbn)
예제 #17
0
 def test_search_isbn(self):
     search_book = BookRecord(isbn=fake.isbn(),
                              title="Find XYZ Inside",
                              publisher="Creative Awesome",
                              publish_year=2017,
                              author=[Person("Munroe", "Randall")],
                              genre="Test")
     create_book(librarian.db.session, search_book, self.admin_user)
     librarian.db.session.flush()
     results = api.search(search_book.isbn)
     self.assertEqual(len(results), 1)
     self.assertEqual(results[0]["isbn"], search_book.isbn)
예제 #18
0
def edit_books():
    form = EditBookForm()
    book_id = request.args.get("bid")

    if not book_id:
        return flask.abort(400)

    book_query = BookRecord.base_assembler_query().filter(Book.id == book_id)
    query_results = book_query.all()
    assembled = BookRecord.assembler(query_results)

    if not assembled:
        return flask.abort(400)
    elif len(assembled) > 1:
        raise InvalidRecordState("book id %s" % book_id)

    book = assembled[0]
    book_js = "var bookForEditing = JSON.parse(%s)" % json.dumps(
        json.dumps(book.__dict__))

    scripts = [
        "jquery.validate.min.js", "jquery.form.min.js", "Queue.js",
        "types/book-details.js", "edit-book/main.js",
        "edit-book/controller.js", "utils/visual-queue.js", "utils/misc.js",
        "utils/isbn-verify.js", "jquery-ui.min.js", "lodash.js",
        "alertify.min.js", "types/person.js"
    ]

    if app.config["DEVEL"]:
        scripts.insert(0, "add-books/testdata.js")

    styles = ("add_books.css", "jquery-ui.min.css",
              "jquery-ui.structure.min.css", "jquery-ui.theme.min.css",
              "alertify.css", "alertify-default-theme.css")
    return render_template("edit-book.jinja",
                           form=form,
                           scripts=scripts,
                           stylesheets=styles,
                           misc_js=book_js,
                           book_title=book.title)
예제 #19
0
    def test_book_adder_utf8(self):
        self.make_current_user()
        isbn = fake.isbn()

        # Check that the relevant records do not exist yet
        self.verify_does_not_exist(Book, isbn=isbn)
        self.verify_does_not_exist(Genre, name="English 12")
        self.verify_does_not_exist(Contributor,
                                   lastname="Pérez-Reverte",
                                   firstname="Arturo")
        self.verify_does_not_exist(Contributor,
                                   lastname="de Onís",
                                   firstname="Harriet")
        self.verify_does_not_exist(BookCompany, name="Scholastic")
        self.verify_does_not_exist(BookCompany, name="UP Press")
        author = [Person(lastname="Pérez-Reverte", firstname="Arturo")]
        translator = [Person(lastname="de Onís", firstname="Harriet")]
        single_author = BookRecord(isbn=isbn,
                                   title="The Club Dumas",
                                   genre="English 12",
                                   author=author,
                                   translator=translator,
                                   publisher="Scholastic",
                                   printer="UP Press",
                                   publish_year=2013)

        single_rv = self.client.post("/api/add/books",
                                     data=single_author.request_data())

        self.assertEquals(single_rv._status_code, 200)

        self.verify_inserted(Book, isbn=isbn)
        self.verify_inserted(Genre, name="English 12")
        self.verify_inserted(Contributor,
                             lastname="Pérez-Reverte",
                             firstname="Arturo")
        self.verify_inserted(BookCompany, name="Scholastic")
        self.verify_inserted(BookCompany, name="UP Press")
예제 #20
0
    def test_get_bookrecord(self):
        book = BookFactory()
        librarian.db.session.add(book)
        librarian.db.session.flush()

        author = BookContributionFactory(role=Role.get_preset_role("Author"),
                                         book=book,
                                         creator=self.admin_user)
        librarian.db.session.add(author)

        translator = BookContributionFactory(
            role=Role.get_preset_role("Translator"),
            book=book,
            creator=self.admin_user)
        librarian.db.session.add(translator)

        illustrator = BookContributionFactory(
            role=Role.get_preset_role("Illustrator"),
            book=book,
            creator=self.admin_user)
        librarian.db.session.add(illustrator)

        librarian.db.session.commit()
        librarian.app.logger.debug("book has id %s" % book.id)

        expected_book_record = {
            "isbn": book.isbn,
            "title": book.title,
            "publisher": book.publisher.name,
            "author": [author.contributor.make_plain_person().to_dict()],
            "translator":
            [translator.contributor.make_plain_person().to_dict()],
            "illustrator":
            [illustrator.contributor.make_plain_person().to_dict()],
            "editor": [],
            "id": book.id,
            "genre": book.genre.name,
            "printer": None,
            "year": book.publish_year
        }
        retrieved_book_record = BookRecord.get_bookrecord(book.id)

        self.assertEqual({
            "spam": "spammy",
            "cling": "clingy"
        }, {
            "cling": "clingy",
            "spam": "spammy"
        })
        self.assertEqual(expected_book_record, retrieved_book_record)
예제 #21
0
    def test_book_adder_reactivation(self):
        self.set_current_user(self.admin_user)
        inactive_contributor = ContributorFactory(lastname="Duffer",
                                                  firstname="Matt",
                                                  active=False)
        librarian.db.session.add(inactive_contributor)
        librarian.db.session.flush()

        isbn = fake.isbn()

        # Check that the relevant records do not exist yet
        self.verify_does_not_exist(Book, isbn=isbn)
        self.verify_does_not_exist(Genre, name="Horror")
        self.verify_does_not_exist(BookCompany, name="Netflix")
        self.verify_does_not_exist(BookCompany, name="WWW")
        author = [Person(lastname="Duffer", firstname="Matt")]

        single_author = BookRecord(isbn=isbn,
                                   title="Stranger Things",
                                   genre="Horror",
                                   author=author,
                                   publisher="Netflix",
                                   printer="WWW",
                                   publish_year=2016)

        reactivate = self.client.post("/api/add/books",
                                      data=single_author.request_data())

        self.assertEquals(reactivate._status_code, 200)
        self.verify_inserted(Book, isbn=isbn)
        self.verify_inserted(Genre, name="Horror")
        self.verify_inserted(BookCompany, name="Netflix")
        self.verify_inserted(BookCompany, name="WWW")
        self.verify_inserted(Contributor,
                             lastname="Duffer",
                             firstname="Matt",
                             active=True)
예제 #22
0
    def test_multiple_book_people(self):
        """
        Test adding multiple people for the fields where person names are
        expected. We can assume that records are "fresh".
        """
        self.make_current_user()
        isbn = fake.isbn()
        title = fake.title()

        authors = [make_person_object() for _ in range(4)]
        illustrators = [make_person_object() for _ in range(4)]
        editors = [make_person_object() for _ in range(4)]
        translators = [make_person_object() for _ in range(4)]

        req_data = BookRecord(isbn=isbn,
                              title=title,
                              genre="Multinational",
                              author=authors,
                              illustrator=illustrators,
                              editor=editors,
                              translator=translators,
                              publisher="Scholastic",
                              printer="UP Press",
                              publish_year=2013)

        req_val = self.client.post("/api/add/books",
                                   data=req_data.request_data())
        self.assertEqual(200, req_val.status_code)
        created_book = (librarian.db.session.query(Book).filter(
            Book.isbn == isbn).first())

        self.verify_persons_inserted(authors, "Author", created_book.id)
        self.verify_persons_inserted(illustrators, "Illustrator",
                                     created_book.id)
        self.verify_persons_inserted(editors, "Editor", created_book.id)
        self.verify_persons_inserted(translators, "Translator",
                                     created_book.id)
예제 #23
0
    def test_same_person_diff_roles(self):
        self.make_current_user()
        jtamaki_exists = (librarian.db.session.query(Contributor).filter(
            Contributor.firstname == "Jillian").filter(
                Contributor.lastname == "Tamaki").first())
        self.assertFalse(jtamaki_exists)

        jtamaki = Person(lastname="Tamaki", firstname="Jillian")
        author_illus = BookRecord(isbn="9781596437746",
                                  title="This One Summer",
                                  genre="Graphic Novel",
                                  author=[jtamaki],
                                  illustrator=[jtamaki],
                                  publisher="First Second",
                                  publish_year=2016)
        rv = self.client.post("/api/add/books",
                              data=author_illus.request_data())

        self.assertEquals(200, rv.status_code)

        jtamakis = (librarian.db.session.query(Contributor).filter(
            Contributor.firstname == "Jillian").filter(
                Contributor.lastname == "Tamaki").all())
        self.assertEqual(1, len(jtamakis))
예제 #24
0
def get_books():
    """
    Get a listing of books in the database.

    Request parameters:
        offset - Integer. The "page number" used for pagination. Default 0.
        limit - Integer. The number of records to return. Default 8.
        order - String, either "desc" or "asc". The order in which to return
        records. Sorting is always alphabetical by the title of the book.
        Default "asc".

    Possible responses:
        200 - Will have accompanying JSON data of the books.
        400 - Parameters not as expected. An accompanying error message will
        specify the unexpected parameters.
        500 - Standard server error.
    """
    offset = "0"
    limit = "8"

    try:
        offset = int(request.args.get("offset", "0"))
        limit = int(request.args.get("limit", "8"))
    except ValueError:
        return (
            "offset and limit must be integers, given (offset: %s, limit: %s)"
            % (offset, limit), 400)

    order = request.args.get("order", "asc")

    if order not in ("desc", "asc"):
        return "order can only be either 'desc' or 'asc', given %s" % order, 400

    bookq = db.session.query(Book)

    if order == "desc":
        bookq = bookq.order_by(desc("title"))
    elif order == "asc":
        bookq = bookq.order_by(asc("title"))

    bookq = bookq.limit(limit).offset(offset * limit)
    books = bookq.all()
    book_listing = [BookRecord.get_bookrecord(book.id) for book in books]
    none_count = sum([1 for book in book_listing if book is None])
    app.logger.info("none count: %s" % none_count)
    book_listing = [book for book in book_listing if book is not None]
    app.logger.debug("Got these books" + str(books))
    return flask.jsonify({"data": book_listing})
예제 #25
0
    def test_search_contributor(self):
        search_book = BookRecord(
            isbn=fake.isbn(),
            title="Don Quixote",
            publisher="Instituto Cervantes",
            publish_year=1957,
            author=[Person("de Cervantes Saavedra", "Miguel")],
            genre="Sci-Fi")
        create_book(librarian.db.session, search_book, self.admin_user)
        librarian.db.session.flush()
        results = api.search("Cervantes")
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]["isbn"], search_book.isbn)

        results = api.search("cervantes")
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]["isbn"], search_book.isbn)

        results = api.search("miguel de cervantes")
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0]["isbn"], search_book.isbn)
예제 #26
0
    def test_factory(self):
        title = "World Taekwondo Federation Welterweight"
        publisher_name = "International Olympic Committee"
        self.verify_does_not_exist(Book, title=title)
        self.verify_does_not_exist(Contributor,
                                   lastname="Tazegul",
                                   firstname="Servet")
        self.verify_does_not_exist(BookCompany, name=publisher_name)
        factory_made = BookRecord.factory(isbn=fake.isbn(),
                                          title=title,
                                          publisher=publisher_name,
                                          author=[Person("Tazegul", "Servet")],
                                          genre="Sports",
                                          publish_year=2017)
        self.verify_inserted(Book, title=title)
        self.verify_inserted(Contributor,
                             lastname="Tazegul",
                             firstname="Servet")
        self.verify_inserted(BookCompany, name=publisher_name)

        self.assertTrue(factory_made is not None)
        self.assertTrue(factory_made.id is not None)
예제 #27
0
    def test_deepcopy(self):
        fake = Faker()
        fake.add_provider(BookFieldsProvider)
        authors = [ContributorFactory().make_plain_person() for _ in range(3)]
        book = BookRecord(isbn=fake.isbn(),
                          title=fake.title(),
                          publisher="Firaxis",
                          author=authors,
                          publish_year=2016,
                          genre="Fiction")

        _book = copy.deepcopy(book)
        self.assertTrue(book is not _book)
        original_attrs = book.__dict__
        deepcopy_attrs = _book.__dict__
        attrs = original_attrs.keys()
        self.assertEquals(attrs, deepcopy_attrs.keys())

        for a in attrs:
            orig_type = type(original_attrs[a])
            copy_type = type(deepcopy_attrs[a])
            self.assertTrue(orig_type is copy_type)

            if a in BookRecord.LIST_TYPES:
                original_persons = [
                    Person(**pdict) for pdict in original_attrs[a]
                ]
                deepcopy_persons = [
                    Person(**pdict) for pdict in deepcopy_attrs[a]
                ]
                self.assertEquals(set(original_persons), set(deepcopy_persons))
            else:
                self.assertEquals(original_attrs[a], deepcopy_attrs[a])

        authors.append(Person(firstname="Sid", lastname="Meier"))
        _book.authors = frozenset(authors)
        self.assertNotEquals(book.authors, _book.authors)
예제 #28
0
    def test_genre_adding(self):
        g1 = GenreFactory(name="B Genre")
        g2 = GenreFactory(name="A Genre")
        librarian.db.session.add(g1)
        librarian.db.session.add(g2)
        librarian.db.session.flush()
        self.set_current_user(self.admin_user)

        bgenre_book = BookRecord(isbn=fake.isbn(),
                                 title=fake.title(),
                                 genre=g1.name,
                                 author=[make_person_object()],
                                 publisher="random",
                                 publish_year=2017)
        bgenre_rv = self.client.post("/api/add/books",
                                     data=bgenre_book.request_data())
        self.assertEquals(200, bgenre_rv.status_code)

        agenre_book = BookRecord(isbn=fake.isbn(),
                                 title=fake.title(),
                                 genre=g2.name,
                                 author=[make_person_object()],
                                 publisher="random",
                                 publish_year=2017)
        agenre_rv = self.client.post("/api/add/books",
                                     data=agenre_book.request_data())
        self.assertEquals(200, agenre_rv.status_code)

        bgenre_orm = (librarian.db.session.query(Book).filter(
            Book.isbn == bgenre_book.isbn).first())

        agenre_orm = (librarian.db.session.query(Book).filter(
            Book.isbn == agenre_book.isbn).first())

        self.assertNotEquals(bgenre_orm.genre, agenre_orm.genre)
        self.assertEquals(bgenre_orm.genre.name, g1.name)
        self.assertEquals(agenre_orm.genre.name, g2.name)
예제 #29
0
    def test_remove_duplicate_contributor_team(self):
        """
        Yet another actual test case encountered live.

        For some reason, Preludes and Nocturnes was saved with the same
        Contributors for both Translators and Editors (note that Preludes and
        Nocturnes is not supposed to have Translators). Deleting all
        Translators does not seem to work.

        UPDATE: Looks like it was, indeed, a side-effect of the update code.
        When editing the Translators role, the Editors field is passed, creating
        the discrepancy.
        """
        self.make_current_user()
        # These two are always parallel arrays.
        contributor_objs = [ContributorFactory() for _ in range(3)]
        editors = [co.make_plain_person() for co in contributor_objs]
        the_deleted = contributor_objs[-1]
        book = BookRecord(isbn=fake.isbn(),
                          title=fake.title(),
                          publisher="Mumford and Sons",
                          editor=editors,
                          translator=editors,
                          publish_year=2016,
                          genre="Fiction")
        book_id = create_book(librarian.db.session, book, self.admin_user)
        librarian.db.session.commit()

        editor_role = Role.get_preset_role("Editor")
        translator_role = Role.get_preset_role("Translator")
        book_editors = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == editor_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        book_translators = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == translator_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        editor_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in book_editors
        ])
        self.assertEquals(set(editors), editor_persons)
        self.assertEquals(set(book_editors), set(book_translators))

        # Delete all translators
        edit_data = BookRecord(isbn=book.isbn,
                               title=book.title,
                               publisher=book.publisher,
                               editor=editors,
                               publish_year=book.publish_year,
                               genre=book.genre,
                               id=book_id)
        edit_book = self.client.post("/api/edit/books",
                                     data=edit_data.request_data())
        self.assertEqual(200, edit_book.status_code)

        updated_book_editors = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == editor_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        updated_editor_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in updated_book_editors
        ])
        self.assertEqual(set(editor_persons), updated_editor_persons)
        updated_book_translators = (
            librarian.db.session.query(Contributor).filter(
                BookContribution.book_id == book_id).filter(
                    BookContribution.contributor_id == Contributor.id).filter(
                        BookContribution.role_id == translator_role.id).filter(
                            BookContribution.active).all())
        self.assertEqual(0, len(updated_book_translators))
        # Verify that the BookRecord for the "deleted" contribution remains
        # but inactive.
        for translator in book_translators:
            self.verify_inserted(BookContribution,
                                 book_id=book_id,
                                 contributor_id=translator.id,
                                 role_id=translator_role.id,
                                 active=False)
            self.verify_inserted(Contributor, id=translator.id, active=True)
예제 #30
0
    def test_edit_book_contrib_correction(self):
        """
        Another actual error encountered in testing. We are modifying
        "MIlo Manara" to "Milo Manara" but it would seem that get_or_create
        fetches "MIlo Manara" when given "Milo Manara".
        """
        self.set_current_user(self.admin_user)

        # These two are always parallel arrays.
        contributor_objs = [
            ContributorFactory(lastname="Manara", firstname="MIlo")
        ]
        illustrators = [co.make_plain_person() for co in contributor_objs]
        the_deleted = contributor_objs[-1]
        book = BookRecord(isbn=fake.isbn(),
                          title=fake.title(),
                          publisher="Mumford and Sons",
                          illustrator=illustrators,
                          publish_year=2016,
                          genre="Fiction")
        book_id = create_book(librarian.db.session, book, self.admin_user)
        librarian.db.session.commit()

        illustrator_role = Role.get_preset_role("Illustrator")
        book_illustrators = (librarian.db.session.query(Contributor).filter(
            BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == illustrator_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        illustrator_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in book_illustrators
        ])
        self.assertEquals(set(illustrators), illustrator_persons)

        edited_book_illustrators = [
            Person(lastname="McKean", firstname="Dave"),
            Person(lastname="Manara", firstname="Milo")
        ]
        edit_data = BookRecord(isbn=book.isbn,
                               title=book.title,
                               publisher=book.publisher,
                               illustrator=edited_book_illustrators,
                               publish_year=book.publish_year,
                               genre=book.genre,
                               id=book_id)
        librarian.db.session.commit()
        edit_book = self.client.post("/api/edit/books",
                                     data=edit_data.request_data())
        self.assertEqual(200, edit_book.status_code)

        updated_book_illustrators = (librarian.db.session.query(
            Contributor).filter(BookContribution.book_id == book_id).filter(
                BookContribution.contributor_id == Contributor.id).filter(
                    BookContribution.role_id == illustrator_role.id).filter(
                        BookContribution.active).filter(
                            Contributor.active).all())
        updated_illustrator_persons = set([
            Person(firstname=a.firstname, lastname=a.lastname)
            for a in updated_book_illustrators
        ])
        self.assertEqual(set(edited_book_illustrators),
                         updated_illustrator_persons)
        # Verify that the BookRecord for the "deleted" contribution remains
        # but inactive.
        self.verify_inserted(BookContribution,
                             book_id=book_id,
                             contributor_id=the_deleted.id,
                             role_id=illustrator_role.id,
                             active=False)
        self.verify_inserted(Contributor, id=the_deleted.id, active=False)