def setUp(self): uncle_bob = Author(name='Robert', surname='Martin') uncle_bob.save() mcconnell = Author(name='Steve', surname='McConnell') mcconnell.save() myers = Author(name='Glenford', surname='Myers') myers.save() levi_metthew = Author(name='Levi Metthew') levi_metthew.save() clean_code = Book( name='Clean code', description='How to write <i>code</i> well', price=Decimal('0.01'), link='http://amazons3.com/books/clean_code.pdf', ) clean_code.save() clean_code.authors.add(uncle_bob) code_complete = Book( name='Code complete', description='How to write <i>code</i> well', price=Decimal('0.02'), link='http://amazons3.com/books/code_complete.pdf', ) code_complete.save() code_complete.authors.add(mcconnell) code_complete.authors.add(levi_metthew) the_art_of_software_testing = Book( name='The art of software testing', description='The first book about software testing', price=Decimal('0.003'), link='http://amazons3.com/books/the_art_of_software_testing.pdf') the_art_of_software_testing.save() the_art_of_software_testing.authors.add(myers) the_art_of_software_testing.authors.add(levi_metthew) alobachev = User(username='******', email='*****@*****.**') alobachev.set_password('password') alobachev.save() alobachev.profile.bought_books.add(code_complete) achistyakov = User(username='******', email='*****@*****.**') achistyakov.set_password('password') achistyakov.save() achistyakov.profile.bought_books.add(code_complete, the_art_of_software_testing) aukupnik = User(username='******', email='*****@*****.**') aukupnik.set_password('password') aukupnik.save() aukupnik.profile.bought_books.add(code_complete, the_art_of_software_testing, clean_code) aapostle = User(username='******', email='*****@*****.**') aapostle.set_password('password') aapostle.save() achistyakov.profile.cards.create(name='VISA***1111', payment_number='1111-1111-1111-1111')
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 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)
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']) db.session.add(new_book) db.session.commit() 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 return response return Response("", 400, mimetype="application/json")
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()
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()
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 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')
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)
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'))
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)
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')
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])
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()
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)
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}")
# 책 이름, 이미지 주소 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()
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')
def get_book_by_isbn(isbn) -> Book: response = requests.get(BOOK_ENDPOINT, params={'ISBN': isbn}) return Book(**response.json())
tempDay = random.randint(1, 28) published_date = date(tempYear, tempMonth, tempDay) if len(title) >= 300: title = title[0:295] + '...' books = '{}\n'.format(cnt) books += 'Book Title: {}\n'.format(title) books += 'Pages: {}\n'.format(pages) books += 'Price: {}\n'.format(price) books += 'Rating: {}\n'.format(rating) books += 'Publisher: {}\n'.format(publisher) books += 'Published Date: {}\n'.format(published_date.strftime("%Y-%m-%d")) book = Book() book.book_title = title book.pages = pages book.price = price book.rating = rating book.publisher_id = publisher book.published_date = published_date author_id = [random.randint(1, 1572)] if cnt % 17 == 0: for i in range(1, 3): author_id.append(random.randint(1, 1572)) if cnt % 29 == 0: for i in range(1, 4):
def mocked_books(): return [Book(**book) for book in mocks.MOCKED_BOOKS]
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
def get_all_books() -> List[Book]: response = requests.get(BOOKS_ENDPOINT) if not response.ok: raise ConnectionError(f'Unable to get all books: {response.content}') books = response.json()['books'] return [Book(**book) for book in books]