Esempio n. 1
0
 def test_show_books_list(self, mock_print):
     bk1 = Book('a', 'aaa')
     bk2 = Book('b', 'bbb')
     books = [bk1, bk2]
     ui.show_books(books)
     mock_print.assert_any_call(bk1)
     mock_print.assert_any_call(bk2)
 def test_delete_all_books(self):
     self.clear_bookstore()
     bk1 = Book(title='Not in store', author='Not in store')
     bk2 = Book(title='Whatever', author='Whatever')
     store.add_book(bk1)
     store.add_book(bk2)
     store.delete_all_books()
     self.assertEqual(0, store.book_count())
    def test_delete_all_books(self):
        bk1 = Book(title='Interesting Title', author='Author')
        bk2 = Book(title='Whatever', author='W. Whatever')
        bk1.save()
        bk2.save()

        bookstore.delete_all_books()
        self.assertEqual(0, bookstore.book_count())
Esempio n. 4
0
 def test_delete_all_books(self):
     self.clear_bookstore()
     bk1 = Book('Not in store', 'Not in store')
     bk2 = Book('Whatever', 'Whatever')
     self.BS.add_book(bk1)
     self.BS.add_book(bk2)
     self.BS.delete_all_books()
     self.assertEqual(0, self.BS.book_count())
    def add_test_data(self):
        self.bk1 = Book(title='An Interesting Book', author='Ann Author', read=True)
        self.bk2 = Book(title='Booky Book Book', author='B. Bookwriter', read=False)
        self.bk3 = Book(title='Collection of words', author='Creative Creator')

        self.clear_bookstore()

        store.add_book(self.bk1)
        store.add_book(self.bk2)
        store.add_book(self.bk3)
Esempio n. 6
0
    def add_test_data(self):
        self.bk1 = Book('the title', 'the author', False)
        self.bk2 = Book('what the book is called', 'the writer', True)
        self.bk3 = Book('fascinating', 'the author', True)
        self.bk4 = Book('brilliant', 'schrodinger', False)

        self.store.add_book(self.bk1)
        self.store.add_book(self.bk2)
        self.store.add_book(self.bk3)
        self.store.add_book(self.bk4)
Esempio n. 7
0
    def add_test_data(self):
        self.bk1 = Book('An Interesting Book', 'Ann Author', True)
        self.bk2 = Book('Booky Book Book', 'B. Bookwriter', False)
        self.bk3 = Book('Collection of words', 'Creative Creator')

        self.clear_bookstore()

        self.BS.add_book(self.bk1)
        self.BS.add_book(self.bk2)
        self.BS.add_book(self.bk3)
Esempio n. 8
0
    def test_create_book_id_increases(self):
        Counter.reset_counter()

        bk = Book('Title', 'Author')
        self.assertEqual(1, bk.id)

        bk2 = Book('Title2', 'Author2')
        self.assertEqual(2, bk2.id)

        bk3 = Book('Title3', 'Author3')
        self.assertEqual(3, bk3.id)
Esempio n. 9
0
    def add_test_data(self):
        self.bk1 = Book(title='the title', author='the author', read=False)
        self.bk2 = Book(title='what the book is called',
                        author='the writer',
                        read=True)
        self.bk3 = Book(title='fascinating', author='the author', read=True)
        self.bk4 = Book(title='brilliant', author='schrodinger', read=False)

        store.add_book(self.bk1)
        store.add_book(self.bk2)
        store.add_book(self.bk3)
        store.add_book(self.bk4)
Esempio n. 10
0
def save_book(book: book.Book) -> Book:
    try:
        db_zipfile = ZipFile(zip_name=book.zip_file.zip_name)
        db_session.merge(db_zipfile)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        db_zipfile = db_session.query(ZipFile).filter(
            ZipFile.zip_name == book.zip_file.zip_name).first()
        logging.error(e)
    db_book = Book(zip_name=book.zip_file.zip_name,
                   book_name=book.book_name,
                   title=book.title,
                   annotation=book.annotation,
                   authors=book.authors,
                   language=book.lang,
                   genre=book.genre)

    try:
        db_session.add(db_book)
        db_session.commit()
    except IntegrityError as e:
        db_session.rollback()
        db_book = db_session.query(Book).filter(
            Book.zip_name == book.zip_file.zip_name
            and Book.book_name == book.book_name).first()
        logging.error(e)
    for word in book.words:
        save_book_word(db_book, word)
    db_session.commit()
    return db_book
Esempio n. 11
0
    def search(self, title):
        docs = self.__repo.search(title)
        books = []

        for doc in docs:
            books.append(Book(doc['isbn'], doc['title'], doc['price']))
        return books
Esempio n. 12
0
def create_new_user_submitted_book():
    """Create a new user-submitted book."""

    title = request.form.get('title')
    author = request.form.get('author')

    # Validate if username or email already exists in users table in database
    if not crud.get_book_by_title(title):

        book = Book(title=title)

        db.session.add(book)
        db.session.commit()

        flash('Book submitted successfully!', 'success')

        return redirect("/books")

    # If book does exist, flash message
    else:
        if Book.query.filter_by(title=title).all():
            flash(f"The book you submitted already exists in the library",
                  "warning")

        return redirect("/books")
Esempio n. 13
0
        def _row_to_book(self, row):
            if not row:
                return None
            book = Book(row['title'], row['author'], row['read'] != 0,
                        row['rowid'])

            return book
Esempio n. 14
0
    def test_save_add_to_db(self):
        bk = Book(author='AAAA', title='BBBB', read=True)
        bk.save()
        self.assertIsNotNone(bk.id)  # Check book has ID

        self.assertEqual(bk, bookstore.get_book_by_id(bk.id))
        self.assertTrue(bookstore.exact_match(bk))
Esempio n. 15
0
 def test_add_book(self):
     self.add_test_data()
     book_count = self.BS.book_count()
     bk = Book('aa', 'bbbbb')
     self.BS.add_book(bk)
     self.assertTrue(self.BS.get_book_by_id(bk.id))
     self.assertEqual(book_count + 1, self.BS.book_count())
Esempio n. 16
0
def add_book():
    """Add new book to db"""

    data = request.get_json()
    print(data)
    print("session id: {}".format(session['user_id']))

    q = Book.query.filter((Book.title == data["title"])
                          & (Book.author == data["author"]))

    if q.count() == 0:
        new_book = Book(title=data['title'], author=data['author'])
        db.session.add(new_book)
        db.session.commit()
        new_user_book = BookUser(book_id=new_book.id,
                                 user_id=session['user_id'])
        db.session.add(new_user_book)
        db.session.commit()
        book = {
            'title': data["title"],
            'author': data["author"],
            'id': new_book.id
        }
        return jsonify(book)

    else:
        book = q.one()
        new_user_book = BookUser(book_id=book.id, user_id=session['user_id'])
        db.session.add(new_user_book)
        db.session.commit()
        book = {'title': book.title, 'author': book.author, 'id': book.id}
        return jsonify(book)
Esempio n. 17
0
def load_books():
    """Load users from u.user into database."""

    print("Books")

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicate users
    User.query.delete()

    # Read u.user file and insert data
    for row in open("seed_data/u.book"):
        row = row.rstrip()
        book_id, title, author, isbn, book_cover, book_availability, book_note, user_id = row.split(
            "|")

        book = Book(book_id=book_id,
                    title=title,
                    author=author,
                    ISBN=isbn,
                    book_cover=book_cover,
                    book_availability=True,
                    book_note=book_note,
                    user_id=user_id)

        # We need to add to the session or it won't ever be stored
        db.session.add(book)

    # Once we're done, we should commit our work
    db.session.commit()
 def test_add_book_store_with_books_in(self):
     self.add_test_data()
     book_count = bookstore.book_count()
     bk = Book(title='aa', author='bbbbb')
     bk.save()
     self.assertTrue(bookstore.exact_match(bk))
     self.assertEqual(book_count + 1, bookstore.book_count())
Esempio n. 19
0
def detailsBook(id):
    global apiInfo

    try:
        # Using eval to convert string to a dictionairy
        bookList = json.loads(
            requests.get(app.config['API_ROOT_URL'] + '/books' + '/' +
                         str(id)).content)
    except:
        bookList = []

    for book in bookList:
        # There is one and only one book
        orgBook = Book(
            book['id'],
            book['name'],
            book['price'],  # Two decimals
            book['isbn'],
            book['isObsolete'],
            book['bookType'])

    orgBook.price = ConvertToTwoDecimals(orgBook.price)
    orgBook.isObsolete = ConvertBooleanToText(orgBook.isObsolete)
    orgBook.bookType = ConvertEnumBookTypeToDescription(orgBook.bookType)

    return render_template('books/details.html',
                           actionTitle='Book details',
                           appTitle=app.config['APP_TITLE'],
                           api=apiInfo,
                           book=vars(orgBook))
Esempio n. 20
0
def deleteBook(id):
    global apiInfo

    try:
        bookList = json.loads(
            requests.get(app.config['API_ROOT_URL'] + '/books' + '/' +
                         str(id)).content)
    except:
        bookList = []

    for book in bookList:
        # There is one and only one book
        # Use constructor b/c mutating members directly result in unpredictable data
        orgBook = Book(book['id'], book['name'])

    form = DeleteBookForm()

    if form.validate_on_submit():
        requests.delete(app.config['API_ROOT_URL'] + '/books' + '/' + str(id))

        flash('Deleted book id = {}'.format(id))
        return redirect('/books')

    return render_template('books/delete.html',
                           actionTitle='Delete book',
                           appTitle=app.config['APP_TITLE'],
                           api=apiInfo,
                           book=vars(orgBook),
                           form=form)
Esempio n. 21
0
def create_book(google_id, title, cover_img='/static/no_cover.jpg'):
    book = Book(google_id=google_id, cover_img=cover_img, title=title)

    db.session.add(book)
    db.session.commit()

    return book
Esempio n. 22
0
def extract_books(xml_root):
    def str2int(i):
        return 0 if not i else int(i)

    books = []
    for item in xml_root.iter('item'):
        title = item.find('title').text
        isbn = item.find('isbn').text
        author = item.find('author_name').text
        link = item.find('link').text
        num_pages = item.find('book').find('num_pages').text
        thumbnail_url = item.find('book_medium_image_url').text
        year_published = int(
            get_with_default(item.find('book_published').text, 0))
        user_read_at = parse_date(item.find('user_read_at').text)
        user_read_at_year = user_read_at.year if user_read_at else 0
        books.append(
            Book(title=title,
                 author=author,
                 link=link,
                 isbn=isbn,
                 num_pages=str2int(num_pages),
                 thumbnail_url=thumbnail_url,
                 year_read=user_read_at_year,
                 year_published=year_published))
    return books
Esempio n. 23
0
def create_library():
    with open('library.csv', 'r') as books:
        reader = csv.DictReader(books)

        for row in reader:
            date_str = row['publication_date']
            published_at = datetime.strptime(date_str, '%Y-%m-%d').date()
            image = f'./static/book_img/{row["id"]}'
            try:
                open(f'{image}.png')
                image += '.png'
            except:
                image += '.jpg'

            book = Book(id=int(row['id']),
                        name=row['book_name'],
                        author=row['author'],
                        publisher=row['publisher'],
                        publication_date=published_at,
                        pages=int(row['pages']),
                        isbn=row['isbn'],
                        description=row['description'],
                        link=row['link'],
                        image=image,
                        rating=0,
                        available=5)
            db.session.add(book)

        db.session.commit()
Esempio n. 24
0
    def get_book(self, book_id: str) -> Book:
        r = requests.get(self.__api.get_url('books') + '/' + book_id)
        json_book = r.json()['book']
        chapters = list()
        for json_chapter in json_book['chapters']:
            chapters.append(
                Chapter(id=json_chapter['id'],
                        order_number=json_chapter['order_nr'],
                        title=json_chapter['title'],
                        text=json_chapter['text']))

        book = Book(id=json_book['id'],
                    published_at=json_book['published_at'],
                    title=json_book['title'],
                    subtitle=json_book['subtitle'],
                    author=json_book['author'],
                    language=json_book['language'],
                    about_the_book=json_book['about_the_book'],
                    teaser=json_book['teaser'],
                    who_should_read=json_book['who_should_read'],
                    about_the_author=json_book['about_the_author'],
                    market=json_book['market'],
                    image_url=json_book['image_url'],
                    chapters=chapters)
        return book
Esempio n. 25
0
 def find(self, isbn):
     books = self.__db['books'];
     docs = books.find({'isbn': isbn})
     if docs.count() == 0:
         return None
     doc = docs[0]
     return Book(doc['isbn'], doc['title'], doc['price'])
Esempio n. 26
0
 def test_add_book(self, mock_print, mock_input):
     main.main()
     # reset counter and make book that mimics the one expected to be created
     Counter.reset_counter()
     expected_book = Book('Title', 'Author', False)
     all_books = self.store.get_all_books()
     self.assertEqual(expected_book, all_books[0])
 def test_add_book(self):
     self.add_test_data()
     book_count = store.book_count()
     bk = Book(author='aa', title='bbbbb')
     store.add_book(bk)
     self.assertTrue(store.get_book_by_id(bk.id))
     self.assertEqual(book_count + 1, store.book_count())
Esempio n. 28
0
 def test_add_book_prevent_duplicates(self, mock_print, mock_input):
     main.main()
     self.assertEqual(1, store.book_count())
     # make book that mimics the first one expected to be created
     expected_book = Book(title='Title', author='Author', read=False, id=1)
     all_books = store.get_all_books()
     self.assertEqual(expected_book, all_books[0])
Esempio n. 29
0
def create_book(name, **kwargs):
    owner_id = get_current_user_id()
    if not owner_id:
        return False
    description = kwargs.get('description')
    genres_ids = kwargs.get('genres_ids') or []
    cover_image_url = kwargs.get('cover_image_url')
    page_count = kwargs.get('page_count')
    author_name = kwargs.get('author_name')
    year = kwargs.get('year')

    book = Book(name=name, owner_id=owner_id)
    book.description = description
    book.cover_image_url = cover_image_url
    book.page_count = page_count
    book.author_name = author_name
    book.year = year

    genres = []
    for id in genres_ids:
        g = get_genre_by_id(id)
        if g:
            genres.append(g)
    book.genres = genres

    session.add(book)
    session.commit()
    return book
Esempio n. 30
0
def create_book(google_id, name, subject=None):
    """create and return new user"""

    book = Book(google_id=google_id, name=name, subject=subject)
    db.session.add(book)
    db.session.commit()
    return book