Esempio n. 1
0
    def setUp(self):
        self.user = User(username='******', password='******', email='*****@*****.**')
        self.user.save()

        self.author = Author(first_name='Ernest', last_name='Hemingway')
        self.author.save()

        self.book = Book(title='A Farewell to Arms', author=self.author,
            publication_year=1929)
        self.book.save()

        self.book2 = Book(title='The Sun Also Rises', author=self.author,
            publication_year=1926)
        self.book2.save()

        self.book3 = Book(title='For Whom The Bell Tolls', author=self.author,
            publication_year=1940)
        self.book3.save()

        self.review = Review(
            user=self.user,
            book=self.book,
            timestamp=datetime.datetime.now(),
            review_message='Good Book',
            rating=5
        )
def get_all_books():
    books = []
    if request.method == 'GET':
        print('THis is get request')
        for book in Book.query.all():
            temp_dict = {
                'book_name': book.book_name,
                'book_price': book.book_price,
                'book_num': book.book_num
            }
            books.insert(0, temp_dict)
        return jsonify(books)
    elif request.method == 'POST':
        print('This is post request', request.get_json())
        request_data = request.get_json()
        if valid_book(request_data):
            new_book = Book(book_name=request_data['book_name'],
                            book_price=request_data['book_price'],
                            book_num=request_data['book_num'])
            new_book.save()
            books.append(request.get_json())
            response = Response(
                "", 201,
                mimetype="application/json")  # 201 response i.e created
            response.headers['Location'] = '/books/' + str(
                request_data['book_num'])  # link in the header
            redirect(url_for('get_all_books'))
            return response
        return Response("", 400, mimetype="application/json")
Esempio n. 3
0
 def setUp(self):
     self.book = Book(
         name='Clean code',
         description='How to write <i>code</i> well',
         price=Decimal('0.01'),
         link='http://amazons3.com/rmartin/clean_code.pdf',
     )
     self.book.save()
Esempio n. 4
0
    def testBookNullFields(self):
        """Test whether Book with Null fields is invalidated"""
        #title is Null
        b1 = Book(author=Author(first_name='Ernest', last_name='Hemingway'))
        self.assertRaises(ValidationError, b1.full_clean)

        #author is Null
        b2 = Book(title='A Farewell to Arms')
        self.assertRaises(ValidationError, b2.full_clean)
Esempio n. 5
0
 def test_buy_book(self):
     book = Book(
         name='foo',
         description='bar',
         price=Decimal('0.00001'),
         link='http://example.com/book.pdf',
     )
     book.save()
     self.user.profile.bought_books.add(book)
     self.assertEqual(list(book.buyers.all()), [self.user.profile])
Esempio n. 6
0
def test_cancel_reservation_ok(client, admin_access_token, db_populate_books,
                               db_populate_reservations):
    """
    Test the cancel reservation function.

    :assert: response status code is 204.
    :assert: no content in response.
    :assert: reservation is cancelled.
    """
    book = Book.get_or_404(6)

    response = client.patch(
        f'admin/cancelResBook/{book.id}',
        headers={'Authorization': f'Bearer {admin_access_token}'})

    assert response.status_code == 204
    assert not response.json

    reservation = Reservation.query.filter(
        Reservation.book_id == book.id,
        Reservation.status == "FINISHED").one()
    assert reservation

    with pytest.raises(NoResultFound):
        assert not Reservation.query.filter(Reservation.book_id == book.id,
                                            Reservation.status
                                            == "STARTED").one()
Esempio n. 7
0
    def handle(self, *args, **options):
        Publisher.objects.all().delete()
        Book.objects.all().delete()
        Store.objects.all().delete()

        #Adding Publisher
        publisher = [Publisher(name=f"Publisher {i}") for i in range(1, 6)]
        Publisher.objects.bulk_create(publisher)

        #Adding 20 books for each publisher
        count = 0
        books = []
        for publisher in Publisher.objects.all():
            for i in range(20):
                count += 1
                books.append(
                    Book(name=f"Book {count}",
                         price=random.randint(50, 500),
                         publisher=publisher))
        Book.objects.bulk_create(books)

        #Create 10 Stores and insert 10 books in each Store
        books = list(Book.objects.all())  # All 100 books will come
        for i in range(1, 11):
            ten_books = [
                books.pop(0) for _ in range(10)
            ]  # Will pop 0th element from books 10 times. To get 10 books
            print('ten_books:', ten_books)
            store = Store.objects.create(name=f"Store {i}")
            print('store:', store)
            store.books.set(ten_books)
            store.save()
Esempio n. 8
0
def add_book():
    with open("bookdb/books.csv") as f:
        reader = csv.reader(f)
        header = next(
            reader)  # skip the first line which is a field description
        for item in reader:
            dt = Book(isbn=item[11],
                      title=item[1],
                      author=item[2],
                      publish_date=item[13],
                      average_rating=item[3],
                      ratings_count=item[4],
                      page_count=item[9],
                      description=item[7])
            dt.save()
            print(f"Added {dt.isbn}")
Esempio n. 9
0
    def handle(self, *args, **options):
        Publisher.objects.all().delete()
        Book.objects.all().delete()
        Store.objects.all().delete()

        # create 5 publishers
        publishers = [
            Publisher(name=f"Publisher{index}") for index in range(1, 6)
        ]
        Publisher.objects.bulk_create(publishers)

        # create 20 books for every publishers
        counter = 0
        books = []
        for publisher in Publisher.objects.all():
            for i in range(20):
                counter = counter + 1
                books.append(
                    Book(name=f"Book{counter}",
                         price=random.randint(50, 300),
                         publisher=publisher))

        Book.objects.bulk_create(books)

        # create 10 stores and insert 10 books in every store
        books = list(Book.objects.all())
        for i in range(10):
            temp_books = [books.pop(0) for i in range(10)]
            store = Store.objects.create(name=f"Store{i+1}")
            store.books.set(temp_books)
            store.save()
Esempio n. 10
0
def staff_purchase(request):
    user = request.REQUEST.get('user')
    if user:
        purchases = get_merged_purchases(User.get(pk=user))
    else:
        purchases = Purchase.objects.all()

    book = request.REQUEST.get('book')
    if book:
        purchases = purchases.filter(publication__book=Book.get(pk=book))
        
    status = request.REQUEST.get('status') or 'RSX'
    purchases = purchases.filter(status__in=status)
    
    sort = request.REQUEST.get('sort')
    if sort:
        purchases = purchases.annotate(downloads=Count('download')).order_by(sort.strip("+"))
        
    purchasepager = Pager(request, purchases.count(), pagesize=50)
    purchases = purchases[purchasepager.slice]
    
    toggle_pending = request.GET.copy()
    toggle_pending["status"] = ['RSX', 'PRSCX'][status == 'RSX']
    toggle_pending = '?' + toggle_pending.urlencode()

    return render_to_response("bookstore/staff_purchases.html", locals())
Esempio n. 11
0
def test_reserve_book_400_book_already_reserved(client, admin_access_token,
                                                db_populate_books,
                                                db_populate_reservations):
    """
    Test the reserve book function.

    If book is already reserved:
    :assert: response status code is 400.
    :assert: reservation is not created.
    """

    reservation_before = Reservation.query.filter(
        Reservation.status == 'STARTED').first()

    assert reservation_before

    book = Book.get_or_404(reservation_before.book_id)
    user = User.get_or_404(1)

    response = client.post(
        f'admin/reserveBook/{book.id}/{user.id}',
        headers={'Authorization': f'Bearer {admin_access_token}'})
    assert response.status_code == 400

    #Assert reservations are not changed.
    reservation_after = Reservation.query.filter(
        Reservation.book_id == book.id, Reservation.status == 'STARTED').one()
    assert reservation_before == reservation_after
Esempio n. 12
0
    def testBookString(self):
        """Test whether string representation of Book is correct"""

        b = Book(title='A Farewell to Arms',
                 author=Author(first_name='Ernest', last_name='Hemingway'),
                 publication_year=1929)

        self.assertEqual(str(b), 'A Farewell to Arms')
Esempio n. 13
0
    def test_schema_dump_empty(self, schema, db_populate_books):
        """
        Test schema dump returns an empty list.
        """
        book = Book.get_or_404(1)

        dumped_book = schema.dump(book)
        assert not dumped_book
Esempio n. 14
0
    def testBookNegativePublicationYear(self):
        """Test whether a Book with a negative pub year is invalidated"""

        b = Book(title='A Farewell to Arms',
                 author=Author(first_name='Ernest', last_name='Hemingway'),
                 publication_year=-10)

        self.assertRaises(ValidationError, b.full_clean)
Esempio n. 15
0
def db_populate_reservations(db_populate_books, db):
    """Populate the mock database with reservations data."""

    books = db.session.query(Book).all()
    users = db.session.query(User).all()

    for x in range(len(users)):
        res = Reservation()
        res.book = books[x]
        res.user = users[x]

        books[x].isReserved = True
        users[x].books_amount += 1

        db.session.add(res)
    db.session.commit()
    
    #Make some additional reservations.
    res1 = Reservation()
    res1.user = users[1]
    res1.book = books[6]
    books[6].isReserved = True
    db.session.add(res1)

    res2 = Reservation()
    res2.user = users[0]
    res2.book = books[7]
    books[7].isReserved = True
    db.session.add(res2)

    res3 = Reservation()
    res3.user = users[2]
    res3.book = books[8]
    books[8].isReserved = True
    db.session.add(res3)

    res4 = Reservation()
    res4.user = users[3]
    res4.book = books[9]
    books[9].isReserved = True
    db.session.add(res4)
    
    res5 = Reservation()
    res5.user = users[4]
    res5.book = books[9]
    books[9].isReserved = True
    db.session.add(res5)

    db.session.commit()

    #Mark some reservations as 'Finished'.
    for x in range(1,5):
        res = Reservation.query.get(x)
        res.status='FINISHED'
        book = Book.get_or_404(res.reserved_by)
        book.isReserved = False
    
    db.session.commit()
Esempio n. 16
0
    def testReviewString(self):
        """Test whether string representation of Review is correct"""

        r = Review(user=User(username='******'),
                   book=Book(title='A Farewell to Arms'),
                   timestamp=datetime.datetime.now(),
                   review_message='',
                   rating=1)

        self.assertEqual(str(r), 'guy : A Farewell to Arms')
Esempio n. 17
0
    def testReviewInvalidRating(self):
        """Test whether a review with an invalid rating
        (ie. not 1-5) is invalid"""

        #rating is less than 1
        r1 = Review(user=User(username='******'),
                    book=Book(title='A Farewell to Arms'),
                    timestamp=datetime.datetime.now(),
                    review_message='',
                    rating=0)
        self.assertRaises(ValidationError, r1.full_clean)

        #rating is greater than 5
        r2 = Review(user=User(username='******'),
                    book=Book(title='A Farewell to Arms'),
                    timestamp=datetime.datetime.now(),
                    review_message='',
                    rating=6)
        self.assertRaises(ValidationError, r2.full_clean)
Esempio n. 18
0
class BookModelTest(TestCase):
    def setUp(self):
        self.book = Book(
            name='Clean code',
            description='How to write <i>code</i> well',
            price=Decimal('0.01'),
            link='http://amazons3.com/rmartin/clean_code.pdf',
        )
        self.book.save()

    def test_string_representation(self):
        self.assertEqual(str(self.book), 'Clean code')

    def test_add_few_books_authors(self):
        uncle_bob = Author(name='Robert', surname='Marting')
        uncle_bob.save()
        self.book.authors.add(uncle_bob)
        levi_metthew = self.book.authors.create(name='Levi Matthew')
        self.assertEqual(list(levi_metthew.books.all()), [self.book])
Esempio n. 19
0
def db_populate_books(db):
    """Populate the test database with mock books data."""
    books = []

    for x in range(20):
        books.append(
            Book(title=f'Book{x}', author=f'Author{x}')
        )
    
    db.session.add_all(books)
    db.session.commit()
Esempio n. 20
0
    def test_dump(self, schema, db_populate_books):
        """
        Test schema dumping.
        :assert: schema returns proper data.
        """
        book = Book.get_or_404(1)

        keys_expected = ['id', 'title', 'author', 'pages', 'isReserved']
        keys_returned = schema.dump(book).keys()

        assert len(keys_expected) == len(keys_returned)
        assert set(keys_expected).issubset(set(keys_returned))
Esempio n. 21
0
    def setUp(self):
        self.user = User(username='******',
                         password='******',
                         email='*****@*****.**')
        self.user.save()

        self.author = Author(first_name='Ernest', last_name='Hemingway')
        self.author.save()

        self.book = Book(title='A Farewell to Arms',
                         author=self.author,
                         publication_year=1929)
        self.book.save()

        self.book2 = Book(title='The Sun Also Rises',
                          author=self.author,
                          publication_year=1926)
        self.book2.save()

        self.book3 = Book(title='For Whom The Bell Tolls',
                          author=self.author,
                          publication_year=1940)
        self.book3.save()

        self.review = Review(user=self.user,
                             book=self.book,
                             timestamp=datetime.datetime.now(),
                             review_message='Good Book',
                             rating=5)
Esempio n. 22
0
    def testReviewNullFields(self):
        """Test whether Book with Null fields is invalidated"""

        #user is Null
        r1 = Review(book=Book(title='A Farewell to Arms'),
                    timestamp=datetime.datetime.now(),
                    review_message='',
                    rating=1)
        self.assertRaises(ValidationError, r1.full_clean)

        #book is Null
        r2 = Review(user=User(username='******'),
                    timestamp=datetime.datetime.now(),
                    review_message='',
                    rating=1)
        self.assertRaises(ValidationError, r2.full_clean)

        #timestamp is Null
        r3 = Review(user=User(username='******'),
                    book=Book(title='A Farewell to Arms'),
                    review_message='',
                    rating=1)
        self.assertRaises(ValidationError, r3.full_clean)

        #review_message is Null
        r4 = Review(user=User(username='******'),
                    book=Book(title='A Farewell to Arms'),
                    timestamp=datetime.datetime.now(),
                    rating=1)
        self.assertRaises(ValidationError, r4.full_clean)

        #rating is Null
        r5 = Review(
            user=User(username='******'),
            book=Book(title='A Farewell to Arms'),
            timestamp=datetime.datetime.now(),
            review_message='',
        )
        self.assertRaises(ValidationError, r5.full_clean)
Esempio n. 23
0
def add_book(request, author_id):
    a = Author.objects.get(pk=author_id)
    data = request.POST
    b = Book()
    b.title = data.get("title", "")
    b.author = a
    b.save()

    return HttpResponseRedirect(reverse('books:book_list'))
Esempio n. 24
0
def test_delete_book_401_unauthorized(client, normal_access_token,
                                      db_populate_books):
    """
    Test the delete_book function.

    If user is unauthorized:
    :assert: response status code is 401.
    :assert: book wasn't deleted.
    """
    book = Book.query.get(1)

    response = client.delete(
        'admin/book/' + str(book.id),
        headers={'Authorization': 'Bearer ' + normal_access_token})

    assert response.status_code == 401
    assert Book.get_or_404(1)
Esempio n. 25
0
def test_search_for_books_ok(client, admin_access_token, db_populate_books):
    """
    Test the search_for_books function.

    :assert: response status code is 200.
    :assert: api returns a proper response.
    :assert: expected content was returned.
    """
    payload = {'id': '1', 'title': 'book', 'author': 'someAuthor'}

    expected_content = book_schema.dump(Book.get_or_404(payload['id']))

    response = client.post('admin/searchBooks',
                           headers={
                               'Content-Type': 'application/json',
                               'Authorization': 'Bearer ' + admin_access_token
                           },
                           data=json.dumps(payload))

    assert response.status_code == 200
    content_returned = response.json
    assert expected_content == content_returned
Esempio n. 26
0
def test_reserve_book_401_unauthorized(client, normal_access_token,
                                       db_populate_books):
    """
    Test the reserve_book function.
    
    If user is unauthorized:
    :assert: response status code is 401.
    :assert: reservation is not created.
    """

    book = Book.get_or_404(1)
    user = User.get_or_404(1)

    response = client.post(
        f'admin/reserveBook/{book.id}/{user.id}',
        headers={'Authorization': f'Bearer {normal_access_token}'})

    assert response.status_code == 401
    with pytest.raises(NoResultFound):
        reservation = Reservation.query.filter(
            Reservation.book_id == book.id, Reservation.reserved_by == user.id,
            Reservation.status == 'STARTED').one()
        assert not reservation
Esempio n. 27
0
def test_reserve_book_ok(client, admin_access_token, db_populate_books):
    """
    Test the reserve_book function.

    :assert: response status code is 204.
    :assert: no content is returned.
    :assert: reservation was created.
    """
    book = Book.get_or_404(1)
    user = User.get_or_404(1)

    response = client.post(
        f'admin/reserveBook/{book.id}/{user.id}',
        headers={'Authorization': f'Bearer {admin_access_token}'})

    assert response.status_code == 204
    assert not response.json

    reservation = Reservation.query.filter(
        Reservation.book_id == book.id, Reservation.reserved_by == user.id,
        Reservation.status == 'STARTED').one()

    assert reservation
Esempio n. 28
0
def test_search_for_books_only_id_other_empty_ok(client, admin_access_token,
                                                 db_populate_books):
    """
    Test the search_for_books function.

    If only id is filled and the other fields are empty or consist of only whitespaces:
    :assert: response status code is 200.
    :assert: api returns proper data.
    """
    data = {"id": "1", "author": "", "title": "     "}

    response = client.post('admin/searchBooks',
                           headers={
                               'Content-Type': 'application/json',
                               'Authorization': 'Bearer ' + admin_access_token
                           },
                           data=json.dumps(data))

    assert response.status_code == 200

    data_expected = book_schema.dump(Book.get_or_404(data['id']))
    data_returned = response.json
    assert data_expected == data_returned
Esempio n. 29
0
    def test_schema_load_only(self, schema):
        """Assert schema is load-only."""
        book = Book(title='title', author='author')

        dumped_book = schema.dump(book)
        assert not dumped_book
Esempio n. 30
0
class BookstoreViewsTest(TestCase):
    """Test suite for Bookstore views"""

    def setUp(self):
        self.user = User(username='******', password='******', email='*****@*****.**')
        self.user.save()

        self.author = Author(first_name='Ernest', last_name='Hemingway')
        self.author.save()

        self.book = Book(title='A Farewell to Arms', author=self.author,
            publication_year=1929)
        self.book.save()

        self.book2 = Book(title='The Sun Also Rises', author=self.author,
            publication_year=1926)
        self.book2.save()

        self.book3 = Book(title='For Whom The Bell Tolls', author=self.author,
            publication_year=1940)
        self.book3.save()

        self.review = Review(
            user=self.user,
            book=self.book,
            timestamp=datetime.datetime.now(),
            review_message='Good Book',
            rating=5
        )

    def testIndex(self):
        """Test bookstore index view"""
        response = self.client.get(reverse('bookstore:index'))
        #Just make sure the page loads, that's all
        self.assertEqual(response.status_code, 200)

    def testBookReviewList(self):
        """Test books review list view"""
        #if no book id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:book_review_list'))
        )

        #if the book id is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:book_review_list',
            kwargs = {'book_id':0}
        ))
        self.assertEqual(response.status_code, 404)

        #if the book id is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:book_review_list',
            kwargs = {'book_id':1}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book'].title, 'A Farewell to Arms')

    def testUserReviewList(self):
        """Test user review list view"""
        #if no user id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:user_review_list'))
        )

        #if the user id is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'user_id':0}
        ))
        self.assertEqual(response.status_code, 404)

        #if the username is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'username':'******'}
        ))
        self.assertEqual(response.status_code, 404)

        #if the user id is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'user_id':1}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

        #if the username is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'username':'******'}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

    def testBookList(self):
        """Test book list view"""
        #make sure the context has a list of books, in alphabetical order
        response = self.client.get((reverse('bookstore:book_list')))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book_list'][0].title,
            'A Farewell to Arms')
        self.assertEqual(response.context['book_list'][1].title,
            'For Whom The Bell Tolls')
        self.assertEqual(response.context['book_list'][2].title,
            'The Sun Also Rises')
Esempio n. 31
0
        # 책 이름, 이미지 주소
        img_set[find_img[i].find('a').find('img').get('alt')] = list()
        img_set[find_img[i].find('a').find('img').get('alt')].append(
            find_img[i].find('a').find('img').get('src'))
        # 작가 이름, 주소
        img_set[find_img[i].find('a').find('img').get('alt')].append(
            find_auth[i].find('a').text)
        img_set[find_img[i].find('a').find('img').get('alt')].append(
            find_auth[i].find('a').get('href'))
        # 출판사, 출판일
        img_set[find_img[i].find('a').find('img').get('alt')].append(
            find_pub[i].text)
        img_set[find_img[i].find('a').find('img').get('alt')].append(
            find_date[i].text)

    return img_set


if __name__ == "__main__":
    img = get_all()
    #print(img.items())

    for title, others in img.items():
        print(title, others)
        Book(title=title,
             link=others[0],
             author_name=others[1],
             author_link=others[2],
             pub_name=others[3],
             pub_date=others[4]).save()
from bookstore.models import Author, Book

some_author = Author(name='Chris Conlan')
some_author.save()

some_book = Book(author=some_author,
                 title='Fast Python',
                 subtitle='Re-learn the basics')
some_book.save()
Esempio n. 33
0
    def test_add_book_and_review(self):
        num_cat = Category.objects.filter(owner='kati')
        self.assertEqual(num_cat.count(), 0)

        first_cat = Category(name='Novel', owner='kati')
        first_cat.save()

        num_cat = Category.objects.filter(owner='kati')
        self.assertEqual(num_cat.count(), 1)

        first_book = Book(title='The Thief of Baramos',
                          author='Rabbit',
                          owner='kati',
                          category=num_cat[0])
        first_book.save()
        book = Book.objects.filter(owner='kati')
        self.assertEqual(book.count(), 1)

        second_book = Book(title='The Thief of Baramos vol2',
                           author='Rabbit',
                           owner='kati',
                           category=num_cat[0])
        second_book.save()
        book = Book.objects.filter(owner='kati')
        self.assertEqual(book.count(), 2)

        first_review = Review(book=book[0],
                              timestamp=timezone.now(),
                              review_message='สนุกมาก',
                              rating=4)
        first_review.save()

        avg = Book.objects.filter(id=book[0].id).update(
            avg_rating=Review.objects.filter(book=book[0]).aggregate(
                Avg('rating')).get('rating__avg', 0.00))
        update = Book.objects.filter(id=book[0].id).update(
            update_review=timezone.now())

        second_review = Review(book=book[1],
                               timestamp=timezone.now(),
                               review_message='สนุกมาก',
                               rating=4)
        second_review.save()

        third_review = Review(book=book[1],
                              timestamp=timezone.now(),
                              review_message='สนุกมาก',
                              rating=5)
        third_review.save()

        avg = Book.objects.filter(id=book[1].id).update(
            avg_rating=Review.objects.filter(book=book[1]).aggregate(
                Avg('rating')).get('rating__avg', 0.00))
        update = Book.objects.filter(id=book[1].id).update(
            update_review=timezone.now())

        num_review = Review.objects.all()
        self.assertEqual(num_review.count(), 3)
        self.assertEqual(book[0].avg_rating, 4)
        self.assertEqual(book[1].avg_rating, 4.5)

        response = self.client.post('/kati/2/')
        self.assertEqual(response.templates[0].name,
                         'bookstore/display_title.html')