Example #1
0
    def get_book(self, gnucash_file):
        xml_book = gnucash_file.find('gnc:book', self.ns)
        book_id = xml_book.find('book:id', self.ns).text

        book = self.book_repository.find_by_id(book_id)

        if not book:
            book = Book()
            book.id = book_id

        xml_comodity = xml_book.find('gnc:commodity', self.ns)
        book.comodity = self.get_comodity(xml_comodity)

        return book, xml_book
Example #2
0
 def map_raw_to_book(self, book_raw: Dict):
     return Book(
         **{
             "id":
             str(book_raw["_id"]) if "_id" in book_raw else None,
             "title":
             book_raw["title"] if "title" in book_raw else None,
             "isbn":
             book_raw["isbn"] if "isbn" in book_raw else None,
             "page_count":
             book_raw["page_count"] if "page_count" in book_raw else None,
             "published_date":
             book_raw["published_date"] if "published_date" in
             book_raw else None,
             "thumbnail_url":
             book_raw["thumbnail_url"] if "thumbnail_url" in
             book_raw else None,
             "short_description":
             book_raw["short_description"] if "short_description" in
             book_raw else None,
             "long_description":
             book_raw["long_description"] if "long_description" in
             book_raw else None,
             "status":
             book_raw["status"] if "status" in book_raw else None,
             "authors":
             book_raw["authors"] if "authors" in book_raw else None,
             "categories":
             book_raw["categories"] if "categories" in book_raw else None
         })
Example #3
0
 def map_raw_to_book(self, book_raw: Dict):
     return Book(
         **{
             "id":
             str(self.is_key_in_dict(key="_id", book_raw=book_raw)),
             "title":
             self.is_key_in_dict(key="title", book_raw=book_raw),
             "isbn":
             self.is_key_in_dict(key="isbn", book_raw=book_raw),
             "page_count":
             self.is_key_in_dict(key="page_count", book_raw=book_raw),
             "published_date":
             self.is_key_in_dict(key="published_date", book_raw=book_raw),
             "thumbnail_url":
             self.is_key_in_dict(key="thumbnail_url", book_raw=book_raw),
             "short_description":
             self.is_key_in_dict(key="short_description",
                                 book_raw=book_raw),
             "long_description":
             self.is_key_in_dict(key="long_description", book_raw=book_raw),
             "status":
             self.is_key_in_dict(key="status", book_raw=book_raw),
             "authors":
             self.is_key_in_dict(key="authors", book_raw=book_raw),
             "categories":
             self.is_key_in_dict(key="categories", book_raw=book_raw),
         })
Example #4
0
 def update(self, book_id: str, book: Book):
     updated_result = self.collection.update_one(
         {"_id": ObjectId(book_id)},
         {"$set": book.dict(exclude_unset=True)})
     if updated_result.modified_count == 0:
         raise NoBookUpdateError
     return book_id
Example #5
0
def read_input_file(input_file: str):
    manager = DataManager("./gitignored_folder")
    save_name = input_file.split("data")[1].replace(".txt",
                                                    "").replace("/", "")
    data = manager.load_python_obj(save_name)

    if data is None:

        with open(input_file) as f:
            # Read line 1
            num_books, num_libs, max_days = map(
                lambda x: int(x),
                f.readline().strip().split(' '))
            book_scores = list(
                map(lambda x: int(x),
                    f.readline().strip().split(' ')))
            books = []
            for idx, elem in enumerate(book_scores):
                books.append(Book(id=idx, score=elem))
            book_score_list = np.asarray(book_scores)
            book_scores = {x.id: x._score for x in books}

            libs = []
            for idx in range(num_libs):
                # Read library stats
                n_books_lib, signup_days, amount_of_books_per_day = map(
                    lambda x: int(x),
                    f.readline().strip().split(' '))
                # Read books which are in that particular library
                lib_books = list(
                    map(lambda x: int(x),
                        f.readline().strip().split(' ')))
                lib_books = np.asarray(lib_books)

                score_of_books_in_lib = book_score_list[lib_books]
                sorted_indexes = sorted(range(len(score_of_books_in_lib)),
                                        key=lambda k: score_of_books_in_lib[k])
                sorted_books_based_on_score = lib_books[sorted_indexes]
                sorted_books_based_on_score = np.flip(
                    sorted_books_based_on_score)

                new_library = Library(
                    book_ids=sorted_books_based_on_score,
                    signup_days=signup_days,
                    amount_of_books_per_day=amount_of_books_per_day,
                    id=idx)

                new_library.scores_sum = sum(
                    [book_scores[book_id] for book_id in lib_books])
                libs.append(new_library)

        manager.save_python_obj((num_books, num_libs, max_days, books, libs),
                                save_name)

        return num_books, num_libs, max_days, books, libs

    else:

        return data
 def create_book(self, book: Book) -> Book:
     sql = """INSERT INTO book (title,author,available,return_date,book_condition) VALUES (%s,%s,%s,%s,%s) RETURNING book_id"""
     cursor = connection.cursor()
     cursor.execute(sql, (book.title, book.author, book.available, 0, book.quality))
     connection.commit()
     book_id = cursor.fetchone()[0]
     book.book_id = book_id
     return book
Example #7
0
 def put_book(book_id: str):
     try:
         book = Book.json_deserialize(request.json)
         book.book_id = int(book_id)
         book_service.update_book(book)
         return jsonify(book.json())
     except ResourceNotFound as e:
         return e.message, 404
Example #8
0
    def test_on_success(self):
        EXPECTED_SENDER = 'ANY_SENDER'
        self.usecase.event = {'sender': {'id': EXPECTED_SENDER}}
        book = Book()

        self.usecase.on_success(book)

        assert self.send_api_gateway.send_text_message.call_args[0][0] == EXPECTED_SENDER
Example #9
0
    def post(self):
        try:
            keyword = self.request.get("q")
            if not string.strip(keyword):
                raise AppError(u"キーワードが入力されていません。")

            books = Book.search(keyword)
            self.render_template("add_book.html", {"keyword": keyword, "books": books})
        except AppError, e:
            self.render_template("add_book.html", {"error_msg": e.message})
Example #10
0
 def get(self):
     book_id = self.request.get('id')
     try:
         book = Book.get_by_key_name(book_id)
         if not book:
             raise AppError(u'指定された本は見つかりませんでした。')
         users = UsersBook.get_by_book_id(book_id)
         self.render_template('show_book.html', {'book': book, 'users': users})
     except AppError, e:
         self.render_template('error.html', {'error_msg': e.message})
Example #11
0
 def get(self):
     book_id = self.request.get('id')
     try:
         book = Book.get_by_key_name(book_id)
         if not book:
             raise AppError(u'指定された本は見つかりませんでした。')
         users = UsersBook.get_by_book_id(book_id)
         self.render_template('show_book.html', {
             'book': book,
             'users': users
         })
     except AppError, e:
         self.render_template('error.html', {'error_msg': e.message})
    def get_book_by_id(self, book_id: int) -> Book:
        sql = """SELECT * from book WHERE book_id = %s"""
        cursor = connection.cursor()
        cursor.execute(sql, [book_id])
        records = cursor.fetchall()

        book_list = []

        for book in records:
            book = Book(book[0], book[5], book[1], book[2], book[3], book[4])
            book_list.append(book)

        return book_list[0]
    def get_all_books(self) -> List[Book]:
        sql = """SELECT * from book"""
        cursor = connection.cursor()
        cursor.execute(sql)
        records = cursor.fetchall()

        book_list = []

        for book in records:
            book = Book(book[0], book[5], book[1], book[2], book[3], book[4])
            book_list.append(book)

        return book_list
Example #14
0
    def post(self):
        try:
            keyword = self.request.get('q')
            if not string.strip(keyword):
                raise AppError(u'キーワードが入力されていません。')

            books = Book.search(keyword)
            self.render_template('add_book.html', {
                'keyword': keyword,
                'books': books
            })
        except AppError, e:
            self.render_template('add_book.html', {'error_msg': e.message})
Example #15
0
 def get(self):
     try:
         book_id = self.request.get("id")
         if book_id:
             user = basic_auth.get_current_user()
             book = Book.get_by_key_name(book_id)
             if not book:
                 raise AppError(u"指定された本は見つかりませんでした。")
             ubook = UsersBook(key_name=book_id + ":" + user.email, user=user, book_id=book_id)
             ubook.put()
             self.redirect("/list_book")
         else:
             self.render_template("add_book.html")
     except AppError, e:
         self.render_template("error.html", {"error_msg": e.message})
Example #16
0
 def get(self):
     try:
         book_id = self.request.get('id')
         if book_id:
             user = basic_auth.get_current_user()
             book = Book.get_by_key_name(book_id)
             if not book:
                 raise AppError(u'指定された本は見つかりませんでした。')
             ubook = UsersBook(key_name=book_id + ':' + user.email,
                               user=user,
                               book_id=book_id)
             ubook.put()
             self.redirect('/list_book')
         else:
             self.render_template('add_book.html')
     except AppError, e:
         self.render_template('error.html', {'error_msg': e.message})
Example #17
0
    def test_import_url_success(self):
        EXPECTED_URL = 'ANY_URL'
        EXPECTED_BOOK = Book()
        EXPECTED_ACCOUNT = Mock()
        xml_account = Mock()
        xml_book = Mock()
        xml_book.findall = MagicMock(return_value=[xml_account])
        self.http_client.get_from_url = MagicMock(return_value=Mock())
        self.usecase.get_book = MagicMock(return_value=(EXPECTED_BOOK,
                                                        xml_book))
        self.usecase.get_account = MagicMock(return_value=EXPECTED_ACCOUNT)
        callback = Mock(ImportUrlCallback)

        self.usecase.import_url(EXPECTED_URL, callback)

        self.http_client.get_from_url.assert_called_with(EXPECTED_URL)
        self.book_repository.update_or_create.assert_called_with(EXPECTED_BOOK)
        callback.on_success.assert_called_with(EXPECTED_BOOK)
Example #18
0
 def get(self):
     try:
         user = basic_auth.get_current_user()
         email = self.request.get('email')
         if email:
             if user.email == email:
                 self.redirect('/list_book')
                 return
             else:
                 friend = User.get_by_key_name(email)
                 if not friend:
                     raise AppError(u'指定されたメールアドレスに該当するユーザはいません。')
                 ubooks = UsersBook.get_by_user(friend)
         else:
             friend = None
             ubooks = UsersBook.get_by_user(user)
         books = [Book.get_by_key_name(ubook.book_id) for ubook in ubooks]
         self.render_template('list_book.html', {'books': books, 'friend': friend})
     except AppError, e:
         self.render_template('list_book.html', {'error_msg': e.message})
Example #19
0
 def get(self):
     try:
         user = basic_auth.get_current_user()
         email = self.request.get('email')
         if email:
             if user.email == email:
                 self.redirect('/list_book')
                 return
             else:
                 friend = User.get_by_key_name(email)
                 if not friend:
                     raise AppError(u'指定されたメールアドレスに該当するユーザはいません。')
                 ubooks = UsersBook.get_by_user(friend)
         else:
             friend = None
             ubooks = UsersBook.get_by_user(user)
         books = [Book.get_by_key_name(ubook.book_id) for ubook in ubooks]
         self.render_template('list_book.html', {
             'books': books,
             'friend': friend
         })
     except AppError, e:
         self.render_template('list_book.html', {'error_msg': e.message})
Example #20
0
 def create(self, book: Book):
     inserted_result = self.collection.insert_one(
         book.dict(exclude_unset=True))
     inserted_id = str(inserted_result.inserted_id)
     return inserted_id
Example #21
0
 def post_book():
     book = Book.json_deserialize(request.json)
     book_service.register_book(book)
     app.logger.info(f'new book registered ID: {book.book_id}')
     return jsonify(book.json()), 201
Example #22
0
 def create_book(self, book: Book) -> Book:
     BookDaoLocal.id_maker += 1
     book.book_id = BookDaoLocal.id_maker
     BookDaoLocal.book_table[book.book_id] = book
     return book
Example #23
0
 def register_book(self, book: Book) -> Book:
     book.available = True
     book.return_date = 0
     return self.book_dao.create_book(book)
Example #24
0
 def addBook(self, bookId, title, author, description):
     book = Book(bookId, title, author, description)
     self.__validBook.validate(book)
     self.__repoBook.storeBook(book)
from daos.book_dao_postgres import BookDaoPostgres
from entities.book import Book

book_dao = BookDaoPostgres()
test_book = Book(0,'Dracula','Bram Stoker',True,2,0)

class TestBookDAO:

    def test_create_book(self):
        book_dao.create_book(test_book)
        assert test_book.book_id != 0

    def test_get_by_id(self):
        retrieved_book =book_dao.get_book_by_id(test_book.book_id)
        assert test_book.title == retrieved_book.title

    def test_update_book(self):
        test_book.available = False
        updated_book = book_dao.update_book(test_book)
        assert updated_book.available == test_book.available

    def test_delete_book(self):
        result = book_dao.delete_book_by_id(test_book.book_id)
        assert result == True