Ejemplo n.º 1
0
    def test_get_all_transactions(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 2, 13.1, "book2")
            book2.save_to_db()

            isbns = [self.book.isbn, book2.isbn]
            prices = [self.book.precio, book2.precio]
            quantities = [1, 1]
            TransactionsModel.save_transaction(self.user.id, isbns, prices,
                                               quantities)

            res = self.client.get(
                "/api/allTransactions",
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(200, res.status_code)

            allTransactions = TransactionsModel.query.all()
            for i, transaction in enumerate(allTransactions):
                self.assertEqual(transaction.json(),
                                 json.loads(res.data)['transactions'][0][i])
Ejemplo n.º 2
0
    def basic_setup(self):
        self.user = UsersModel("test",
                               "*****@*****.**",
                               role=Roles.Admin)
        self.user.hash_password("test")
        self.user.save_to_db()
        self.user2 = UsersModel("test2", "*****@*****.**", role=Roles.User)
        self.user2.hash_password("test2")
        self.user2.save_to_db()

        self.book = BooksModel(1, 100, 1, "book1")
        self.book.save_to_db()
        self.book2 = BooksModel(2, 50, 13.1, "book2")
        self.book2.save_to_db()

        res = self.client.post("/api/login",
                               data={
                                   "email": self.user.email,
                                   "password": "******"
                               })
        self.token = json.loads(res.data)["token"]
        res = self.client.post("/api/login",
                               data={
                                   "email": self.user2.email,
                                   "password": "******"
                               })
        self.token2 = json.loads(res.data)["token"]
Ejemplo n.º 3
0
    def test_post_add_library(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 10, 13.1, "book2")
            book2.save_to_db()

            isbns = [self.book.isbn, book2.isbn]
            prices = [self.book.precio, book2.precio]
            quantities = [1, 1]
            dataTransaction = {
                "isbns": isbns,
                'prices': prices,
                'quantities': quantities,
                "email": self.user.email,
            }
            res = self.client.post(
                "/api/transaction",
                data=dataTransaction,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)
            self.assertEqual(self.book.isbn, self.user.library[0].isbn)
            self.assertEqual(book2.isbn, self.user.library[1].isbn)
            self.assertEqual(2, len(self.user.library))
Ejemplo n.º 4
0
    def test_order_mail(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 2, 13.1, "book2")
            book2.save_to_db()

            isbns = [self.book.isbn, book2.isbn]
            prices = [self.book.precio, book2.precio]
            quantities = [1, 1]
            dataTransaction = {
                "isbns": isbns,
                'prices': prices,
                'quantities': quantities,
                "email": self.user.email,
            }
            res = self.client.post(
                "/api/transaction",
                data=dataTransaction,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)
            # hi ha dues transaccions amb id 1
            transactions = TransactionsModel.find_by_id(1)
            self.assertEqual(len(transactions), 2)

            # les dues transaccions equivalen als llibres que acabem de posar
            for i, isbn in enumerate(isbns):
                self.assertEqual(
                    TransactionsModel.find_by_id_and_isbn(1, isbn).json(),
                    json.loads(res.data)['transactions'][i])
Ejemplo n.º 5
0
    def test_model_add(self):
        with self.app.app_context():
            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()
            entry = LibraryModel(book.isbn, 1, LibraryType.Bought, State.Dropped)

            entry.save_to_db()
            self.assertEqual(entry, LibraryModel.find_by_id_and_isbn(1, 1))
Ejemplo n.º 6
0
    def test_model_add(self):
        with self.app.app_context():
            date = datetime.now()
            book = BooksModel(1, 1, 1.0, "titulo", "autor", "editorial",
                              "sinposis", "url", date)

            book.save_to_db()
            self.assertEqual(book, BooksModel.find_by_isbn(book.isbn))
Ejemplo n.º 7
0
    def test_model_delete(self):
        with self.app.app_context():
            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()
            entry = LibraryModel(book.isbn, 1, LibraryType.Bought)
            entry.save_to_db()
            entry.delete_from_db()

            self.assertEqual(False, entry.visible)
Ejemplo n.º 8
0
    def test_model_add_duplicate(self):
        with self.app.app_context():
            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()
            entry = LibraryModel(book.isbn, 1, LibraryType.WishList, State.Reading)
            entry.save_to_db()

            same_entry = LibraryModel(book.isbn, 1, LibraryType.WishList, State.Reading)
            with self.assertRaises(Exception):
                same_entry.save_to_db()
Ejemplo n.º 9
0
    def test_model_invalid_update(self):
        with self.app.app_context():
            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()
            entry = LibraryModel(book.isbn, 1, LibraryType.WishList, State.Pending)
            entry.save_to_db()

            with self.assertRaises(Exception):
                data = {"isbn": 1, "user_id": 1, "state": "Pending2", "visible": True, "library_type": "WishList"}
                entry.update_from_db(data)
Ejemplo n.º 10
0
    def test_model_add_no_stock(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 1, 1, "book2")
            book2.save_to_db()

            with self.assertRaises(Exception):
                TransactionsModel.save_transaction(self.user.id,
                                                   [self.book.isbn],
                                                   [self.book.precio], [100])
Ejemplo n.º 11
0
    def basic_setup(self):
        password = "******"
        self.user = UsersModel("test", "test")
        self.user.hash_password(password)
        self.user.save_to_db()

        self.book = BooksModel(1, 1, 1, "test")
        self.book.save_to_db()

        res = self.client.post("/api/login", data={"email": self.user.email, "password": password})
        self.token = json.loads(res.data)["token"]
Ejemplo n.º 12
0
    def test_get_all_transactions_no_admin(self):
        with self.app.app_context():
            user = UsersModel("test",
                              "*****@*****.**",
                              role=Roles.User)
            user.hash_password("test")
            user.save_to_db()
            res = self.client.post("/api/login",
                                   data={
                                       "email": user.email,
                                       "password": "******"
                                   })
            token = json.loads(res.data)["token"]

            book = BooksModel(1, 1, 1, "book1")
            book.save_to_db()
            book2 = BooksModel(2, 2, 13.1, "book2")
            book2.save_to_db()

            isbns = [book.isbn, book2.isbn]
            prices = [book.precio, book2.precio]
            quantities = [1, 1]
            TransactionsModel.save_transaction(user.id, isbns, prices,
                                               quantities)

            res = self.client.get(
                "/api/allTransactions",
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(403, res.status_code)
Ejemplo n.º 13
0
    def test_get_transactions_without_login(self):
        with self.app.app_context():
            user = UsersModel('test', '*****@*****.**')
            user.hash_password('test')
            UsersModel.save_to_db(user)

            book = BooksModel(1, 1, 1.0, "titulo")
            book.save_to_db()

            # no login

            dataTransaction = {}

            res = self.client.post("/api/transaction", data=dataTransaction)
            self.assertEqual(401, res.status_code)
Ejemplo n.º 14
0
 def json(self):
     _ignore = self.isbn  # Forces execution to parse properly the class, fixing the bug of transient data
     atr = self.__dict__.copy()
     del atr["_sa_instance_state"]
     atr['date'] = self.date.strftime('%d-%m-%Y')
     atr['book'] = BooksModel.find_by_isbn(atr['isbn']).json()
     return atr
Ejemplo n.º 15
0
 def get(self, isbn):
     data = parse_reviews()
     with lock:
         book = BooksModel.find_by_isbn(isbn)
     if not book:
         return {"message": f"Book with ['isbn':{isbn}] not found"}, 404
     return {"book": book.json(**data)}, 200
Ejemplo n.º 16
0
    def save_transaction(cls, user_id, isbns, prices, quantities):
        transactions = []
        email_trans = []
        for isbn, price, quantity in zip(isbns, prices, quantities):
            book = BooksModel.find_by_isbn(isbn)
            cls.check_stock(book, quantity)
            transaction = TransactionsModel(user_id, isbn, price, quantity)
            transactions.append(transaction.json())
            email_trans.append(transaction.email_text())
            db.session.add(transaction)
            user = UsersModel.find_by_id(user_id)

            book_library = LibraryModel.find_by_id_and_isbn(
                user.id, transaction.isbn)
            if book_library:  # if the book was already in library
                if book_library.library_type == LibraryType.WishList:  # if it was in the wish list
                    book_library.library_type = LibraryType.Bought  # change it to bought
                    book_library.state = State.Pending
            else:  # if it wasnt in the library, enter it
                entry = LibraryModel(book.isbn, user.id, LibraryType.Bought,
                                     State.Pending)
                db.session.add(entry)

        cls.it_transaction += 1
        db.session.commit()
        cls.send_email(user_id, email_trans)
        return transactions
Ejemplo n.º 17
0
    def test_post_book_with_minimum_attributes(self):
        with self.app.app_context():
            self.admin_setup()

            isbn = 9780553803716
            data = {
                "isbn": isbn,
                "stock": 10,
                "precio": 7.79,
                "titulo": "Foundation",
            }

            res = self.client.post(
                "/api/book",
                data=data,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)
            self.assertEqual(
                BooksModel.find_by_isbn(isbn).json(), json.loads(res.data))

            res = self.client.post(
                "/api/book",
                data=data,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(409, res.status_code)
Ejemplo n.º 18
0
    def test_model_add_some(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 1, 1, "book2")
            book2.save_to_db()

            expected = TransactionsModel.save_transaction(
                self.user.id, [self.book.isbn, book2.isbn],
                [self.book.precio, book2.precio], [1, 1])
            self.assertEqual(
                expected[0],
                TransactionsModel.find_by_id_and_isbn(1,
                                                      self.book.isbn).json())
            self.assertEqual(expected[1],
                             TransactionsModel.find_by_id_and_isbn(
                                 1, book2.isbn).json())  # same id
Ejemplo n.º 19
0
    def test_basic_put_book(self):
        with self.app.app_context():
            self.basic_setup()
            res = self.client.post(
                "/api/book",
                data=self.data_old,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)

            self.assertEqual(
                BooksModel.find_by_isbn(self.isbn).json(),
                json.loads(res.data))
            res = self.client.put(
                f"/api/book/{self.isbn}",
                data=self.data_new,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(200, res.status_code)
Ejemplo n.º 20
0
    def test_basic_put_book_vendible(self):
        with self.app.app_context():
            self.basic_setup()
            data_new = {
                "sinopsis": self.sinopsis,
                "precio": 8.60,
                "stock": 9,
                "vendible": False
            }

            res = self.client.post(
                "/api/book",
                data=self.data_old,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)
            self.assertEqual(
                BooksModel.find_by_isbn(self.isbn).json(),
                json.loads(res.data))

            res = self.client.put(
                f"/api/book/{self.isbn}",
                data=self.data_new,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(200, res.status_code)
Ejemplo n.º 21
0
    def post(self, email):
        data = parse_entry()
        with lock:
            user = check_user(email)

            if not BooksModel.find_by_isbn(data['isbn']):
                return {
                    "message": f"Book with ['isbn': {data['isbn']}] Not Found"
                }, 404

            if LibraryModel.find_by_id_and_isbn(user.id,
                                                data['isbn']) is not None:
                return {
                    "message":
                    f"Entry with ['email': {email}, 'isbn': {data['isbn']}] already exists"
                }, 409

            data['user_id'] = user.id
            try:
                entry = LibraryModel(**data)
                entry.save_to_db()
            except Exception as e:
                return {"message": str(e)}, 500

        return entry.json(), 201
Ejemplo n.º 22
0
    def test_get_transactions_user(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 2, 13.1, "book2")
            book2.save_to_db()

            isbns = [self.book.isbn, book2.isbn]
            prices = [self.book.precio, book2.precio]
            quantities = [1, 1]
            dataTransaction = {
                "isbns": isbns,
                'prices': prices,
                'quantities': quantities,
                "email": self.user.email,
            }

            res = self.client.post(
                "/api/transaction",
                data=dataTransaction,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)

            res = self.client.get(
                f"/api/transactions/{self.user.email}",
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(200, res.status_code)
            # l'usuari te dues transactions
            self.assertEqual(2, len(self.user.transactions))

            # comprovem que son les que hem acabat d'afegir
            expected = [
                transaction.json()
                for transaction in TransactionsModel.find_by_id(1)
            ]
            real_output = [
                transaction.json() for transaction in self.user.transactions
            ]
            self.assertEqual(expected, real_output)
Ejemplo n.º 23
0
    def test_post_book(self):
        with self.app.app_context():
            self.admin_setup()

            sinopsis = "For twelve thousand years the Galactic Empire has ruled supreme. Now it is dying. But only " \
                       "Hari Seldon, creator of the revolutionary science of psychohistory, can see into the future " \
                       "-- to a dark age of ignorance, barbarism, and warfare that will last thirty thousand years. " \
                       "To preserve knowledge and save mankind, Seldon gathers the best minds in the Empire -- both " \
                       "scientists and scholars -- and brings them to a bleak planet at the edge of the Galaxy to " \
                       "serve as a beacon of hope for a future generations. He calls his sanctuary the " \
                       "Foundation.\nBut soon the fledgling Foundation finds itself at the mercy of corrupt warlords " \
                       "rising in the wake of the receding Empire. Mankind's last best hope is faced with an " \
                       "agonizing choice: submit to the barbarians and be overrun -- or fight them and be destroyed. "
            isbn = 9780553803716
            data = {
                "isbn":
                isbn,
                "stock":
                10,
                "precio":
                7.79,
                "titulo":
                "Foundation",
                "autor":
                "Isaac Asimov",
                "editorial":
                "Bantam Books",
                "sinopsis":
                sinopsis,
                "url_imagen":
                "https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1417900846l"
                "/29579.jpg",
                "fecha_de_publicacion":
                "2001-06-01"
            }

            res = self.client.post(
                "/api/book",
                data=data,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)
            self.assertEqual(
                BooksModel.find_by_isbn(isbn).json(), json.loads(res.data))

            res = self.client.post(
                "/api/book",
                data=data,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(409, res.status_code)
Ejemplo n.º 24
0
    def test_model_add_duplicate(self):
        with self.app.app_context():
            date = datetime.now()
            book = BooksModel(1, 1, 1.0, "titulo", "autor", "editorial",
                              "sinposis", "url", date)
            book.save_to_db()

            same_book = BooksModel(1, 1, 1.0, "titulo", "autor", "editorial",
                                   "sinposis", "url", date)
            with self.assertRaises(Exception):
                same_book.save_to_db()
Ejemplo n.º 25
0
    def basic_setup(self):
        password = "******"
        self.user = UsersModel("test", "test")
        self.user.hash_password(password)
        self.user.save_to_db()

        self.book = BooksModel(1, 10, 10, "test")
        self.book.save_to_db()

        self.entry = LibraryModel(self.book.isbn, self.user.id,
                                  LibraryType.Bought)
        self.entry.save_to_db()

        res = self.client.post("api/login",
                               data={
                                   "email": self.user.email,
                                   "password": password
                               })
        self.token = json.loads(res.data)["token"]
Ejemplo n.º 26
0
    def test_model_update(self):
        with self.app.app_context():
            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()
            book2 = BooksModel(2, 1, 1, "test2")
            book2.save_to_db()

            entry = LibraryModel(book.isbn, 1, LibraryType.Bought, State.Finished)
            entry.save_to_db()

            data = {"isbn": book2.isbn, "user_id": 2, "state": "Reading", "visible": True, "library_type": "WishList"}
            entry.update_from_db(data)

            expected_json = data
            expected_json["book"] = BooksModel.find_by_isbn(book2.isbn).json()
            del expected_json["isbn"]
            self.assertEqual(expected_json, entry.json())
Ejemplo n.º 27
0
    def test_post_entry(self):
        with self.app.app_context():
            user = UsersModel("test", "test")
            user.hash_password("test")
            user.save_to_db()

            book = BooksModel(1, 1, 1, "test")
            book.save_to_db()

            res = self.client.post("api/login", data={"email": user.email, "password": "******"})
            token = json.loads(res.data)["token"]

            parameters = {
                'isbn': book.isbn,
            }

            res = self.client.post(f"api/library/{user.email}", data=parameters, headers={
                "Authorization": 'Basic ' + base64.b64encode((token + ":").encode('ascii')).decode('ascii')
            })
            self.assertEqual(201, res.status_code)
            self.assertEqual(LibraryModel.find_by_id_and_isbn(user.id, 1).json(), json.loads(res.data))
Ejemplo n.º 28
0
 def test_get_search_by_editorial(self):
     with self.app.app_context():
         book = BooksModel(1, 1, 1, "test", "Isaac Asimov", "Bantam Books")
         book.save_to_db()
         book = BooksModel(2, 1, 1, "as")
         book.save_to_db()
         args = {
             'editorial': "Bantam Books"
         }
         res = self.client.get('/api/search', data=args)
         self.assertEqual(200, res.status_code)
         self.assertEqual(len(json.loads(res.data)["books"]), 1)
         list_books = list(map(lambda u: u.json(), BooksModel.query.filter_by(editorial=args['editorial']).all()))
         self.assertEqual(list_books, json.loads(res.data)["books"])
Ejemplo n.º 29
0
 def test_get_search_by_isbn(self):
     with self.app.app_context():
         book = BooksModel(9780553803716, 1, 1, "test")
         book.save_to_db()
         book = BooksModel(9780553803712, 1, 1, "test2")
         book.save_to_db()
         args = {
             "isbn": 9780553803716
         }
         res = self.client.get('/api/search', data=args)
         self.assertEqual(200, res.status_code)
         self.assertEqual(len(json.loads(res.data)["books"]), 1)
         list_books = list(map(lambda u: u.json(), BooksModel.query.filter_by(isbn=args['isbn']).all()))
         self.assertEqual(list_books, json.loads(res.data)["books"])
Ejemplo n.º 30
0
    def test_post_add_library_delete_from_wishlist(self):
        with self.app.app_context():
            self.basic_setup()
            book2 = BooksModel(2, 10, 13.1, "book2")
            book2.save_to_db()

            # enter book to wishlist
            entry = LibraryModel(self.book.isbn, 1, LibraryType.WishList,
                                 State.Pending)
            entry.save_to_db()
            self.assertEqual(entry, LibraryModel.find_by_id_and_isbn(1, 1))

            isbns = [self.book.isbn, book2.isbn]
            prices = [self.book.precio, book2.precio]
            quantities = [1, 1]
            dataTransaction = {
                "isbns": isbns,
                'prices': prices,
                'quantities': quantities,
                "email": self.user.email,
            }
            res = self.client.post(
                "/api/transaction",
                data=dataTransaction,
                headers={
                    "Authorization":
                    'Basic ' + base64.b64encode(
                        (self.token + ":").encode('ascii')).decode('ascii')
                })
            self.assertEqual(201, res.status_code)

            # check if book is in library
            self.assertEqual(self.book.isbn, self.user.library[0].isbn)
            self.assertEqual(book2.isbn, self.user.library[1].isbn)

            # check if type of book2 has changed: was in wishlist, now bought
            self.assertEqual(LibraryType.Bought,
                             self.user.library[1].library_type)

            self.assertEqual(2, len(self.user.library))