Exemple #1
0
def test_edit_user_info(conf):
    info = PersonalDetails(firstname="Serhii",
                           lastname="TestLastName",
                           email="*****@*****.**",
                           telephone="12345")
    conf.personal_details.edit(info)
    assert info == Customer.get_from_db_by_email(info)
    print(Customer.get_from_db_by_email(info))
Exemple #2
0
def test_invalid_data_entry(app):
    invalid_book = Book(price="123",
                        published=datetime.datetime.utcnow(),
                        publisher="Test company")
    with pytest.raises(ValidationError):
        invalid_book.save()
    invalid_customer = Customer(phone="123",
                                customer_since=datetime.datetime.utcnow(),
                                orders=[])
    with pytest.raises(ValidationError):
        invalid_customer.save()
Exemple #3
0
def register():
    """Register a new user.
    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        first_name = request.form["first_name"]
        last_name = request.form["last_name"]
        address = request.form["address"]
        phone = request.form["phone"]
        error = None

        if not email:
            error = "E-mail is required."
        elif not password:
            error = "Password is required."
        elif len(password) < 6:
            error = "Password needs to be more than 6 characters"
        elif not first_name:
            error = "first_name is required."
        elif not last_name:
            error = "last_name is required."
        elif not address:
            error = "address is required."
        elif (Customer.objects(email=email).first() is not None):
            error = "E-mail {0} is already registered.".format(email)

        try:
            if error is None:
                # the name is available, store it in the database and go to
                # the login page
                Customer(first_name=first_name,
                         last_name=last_name,
                         address=address,
                         email=email,
                         password=generate_password_hash(password),
                         phone=phone,
                         customer_since=datetime.datetime.utcnow(),
                         orders=[]).save()

            return redirect(url_for("auth.login"))

        except mongoengine.errors.ValidationError as ex:
            error = ex.errors

        flash(error)

    return render_template("auth/register.html")
Exemple #4
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == "POST":
        email = request.form["email"]
        password = request.form["password"]
        error = None
        user = Customer.objects(email=email).first()

        if user is None:
            error = "Incorrect Email."
        elif not check_password_hash(user["password"], password):
            error = "Incorrect password."

        if error is None:
            # store the user id in a new session and return to the index
            if session.get('order_id'):
                order = Order.objects(id=session.get('order_id')).first()
                order.delete()
            session.clear()
            session["user_id"] = str(user["id"])
            return redirect(url_for("bookstore.index"))

        flash(error)

    return render_template("auth/login.html")
Exemple #5
0
def create_order(user_id, copies, book_id):
    book = Book.objects(id=book_id).first()
    customer = Customer.objects(id=user_id).first()
    books = []
    total = 0.0
    while copies > 0:
        books.append(book)
        total = round(total + Book.objects.with_id(book_id).price, 2)
        copies -= 1
    """checking to see if there's a order id already stored in session"""
    if session.get("order_id"):
        order = Order.objects(id=session.get("order_id")).first()
        order.total_price = round(order.total_price + total, 2)
        for book in books:
            order.books.append(book)
        order.save()
    else:
        order = Order(customer_name="{} {}".format(customer.first_name,
                                                   customer.last_name),
                      books=books,
                      shipping_address=customer.address,
                      total_price=total,
                      order_status="processing",
                      order_date=datetime.datetime.now).save()
        session["order_id"] = str(order.id)

    return order
Exemple #6
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
    else:
        g.user = Customer.objects(id=user_id).first()
Exemple #7
0
def mongo_db_seed(db_name):
    """
    This is a sample mongodb test for populating sample data into mongodb
    :return: the db connection
    """
    mongoengine.connect(db_name, host='localhost', port=27017)
    fake = Faker()

    for x in range(10):
        Book(title=fake.sentence(nb_words=10,
                                 variable_nb_words=True,
                                 ext_word_list=None),
             isbn=fake.isbn13(separator="-"),
             author=fake.name(),
             price=round(random.uniform(0, 100), 2),
             published=datetime.datetime.utcnow(),
             publisher=fake.company()).save()

    for book in Book.objects:
        Inventory(
            book=book.id,
            stock=random.randint(1, 100),
        ).save()

    for x in range(10):
        Customer(first_name=fake.first_name(),
                 last_name=fake.last_name(),
                 address=fake.address(),
                 email=fake.email(),
                 password='******',
                 phone=fake.phone_number(),
                 customer_since=datetime.datetime.utcnow(),
                 orders=[]).save()

    for customer in Customer.objects:
        for x in range(random.randint(1, 5)):
            # the Book.objects.aggregate returns a dict. which is weird...was expecting an obj
            books = [
                book['_id'] for book in Book.objects.aggregate(*[{
                    "$sample": {
                        "size": random.randint(1, 3)
                    }
                }])
            ]
            total = 0.0
            for book in books:
                total = round(total + Book.objects.with_id(book).price)
            order = Order(customer_name="{} {}".format(customer.first_name,
                                                       customer.last_name),
                          books=books,
                          shipping_address=customer.address,
                          total_price=total,
                          order_status="processing",
                          order_date=datetime.datetime.utcnow()).save()
            customer.orders.append(order.id)
            customer.save()
Exemple #8
0
def purchase_books():
    customer = Customer.objects(id=session.get("user_id")).first()
    if session['order_id']:
        order = Order.objects(id=session.get("order_id")).first()
        if len(order.books) < 1:
            flash("Please add some book to cart first")
            return redirect(url_for('bookstore.index'))
    else:
        flash("Please add some book to cart first")
        return redirect(url_for('bookstore.index'))
    customer.orders.append(order)
    customer.save()
    flash("Order complete. The order ID is {}".format(order.id))
    session['order_id'] = None
    return redirect(url_for('bookstore.index'))
Exemple #9
0
def test_valid_data_entry(app):
    book_input = Book(title="Test book title",
                      isbn="Test12345",
                      author="Test author",
                      price="123",
                      published=datetime.datetime.utcnow(),
                      publisher="Test company")
    book_input.save()

    # verify book is successfully saved and able to be retrieved and their values match
    book_saved = Book.objects(title=book_input.title).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify book can be retrieved by isbn
    book_saved = Book.objects(isbn=book_input.isbn).first()
    assert book_saved.title == book_input.title
    assert book_saved.isbn == book_input.isbn
    assert book_saved.author == book_input.author
    assert book_saved.price == book_input.price
    assert book_saved.published.strftime(
        "%m/%d/%Y, %H:%M:%S") == book_input.published.strftime(
            "%m/%d/%Y, %H:%M:%S")
    assert book_saved.publisher == book_input.publisher

    # verify the book can be ordered by a customer
    sample_customer = Customer.objects.first()

    order = Order(customer_name="{} {}".format(sample_customer.first_name,
                                               sample_customer.last_name),
                  books=[book_saved.id],
                  shipping_address=sample_customer.address,
                  total_price=book_saved.price,
                  order_status="processing",
                  order_date=datetime.datetime.utcnow()).save()
    sample_customer.orders.append(order.id)
    sample_customer.save()

    # Look for customer by order. Customer ID should match
    order_customer = Customer.objects(orders=order.id).first()
    assert order_customer.id == sample_customer.id
Exemple #10
0
def create_order(copies, isbn):
    book = Book.objects(isbn=isbn).get()
    customer = Customer.objects(first_name="Kennth").get()
Exemple #11
0
def cur_user_info(id):
    customer = Customer.objects(id=id).first()
    return render_template('bookstore/order.html', orders=customer.orders)