Beispiel #1
0
def index():
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    users_dic_work[current_user.id] = 0
    users_dic_explore[current_user.id] = 0
    if current_user.weapon_id is not None:
        cursor.execute("SELECT * FROM items where id =" +
                       str(current_user.weapon_id))
        res = cursor.fetchone()
        weapon = Item(res)
    else:
        weapon = None
    cursor.execute(
        "select items.id, items.name, items.type, items.value, items.rare\
                    from items, users, armors\
                    where items.id=armors.armor_id and users.id=armors.user_id and users.id=%s"
        % current_user.id)
    res = cursor.fetchall()
    defense = 0
    if len(res) == 0:
        armors = None
    else:
        armors = []
        for i in res:
            armor = Item(i)
            defense = defense + armor.value
            armors.append(armor)
    return render_template("index.html",
                           title='Home Page',
                           weapon=weapon,
                           armors=armors,
                           defense=defense)
def items(db_session):
    camera = Item(
        item_name='Camera Nikon',
        lat=51.5200005,
        lng=-0.0955810994,  # London
        item_url='london/camera',
        img_urls='[camera.jpg]',
        geom=WKTElement('POINT({} {})'.format(-0.0955810994, 51.5200005)))
    db_session.add(camera)
    camera_lenses = Item(
        item_name='Camera Lenses Canon',
        lat=51.752022,
        lng=-1.257677,  # Oxford
        item_url='oxford/camera-lenses',
        img_urls='[camera-lenses.jpg]',
        geom=WKTElement('POINT({} {})'.format(-1.257677, 51.752022)))
    db_session.add(camera_lenses)
    lenses = Item(
        item_name='Lenses Canon',
        lat=34.152231,
        lng=-118.22321,  # LA
        item_url='la/lenses',
        img_urls='[lenses.jpg]',
        geom=WKTElement('POINT({} {})'.format(-118.243683, 34.052235)))
    db_session.add(lenses)
    db_session.commit()
    def setUp(self):
        """ Create test database and set up test client """
        self.app = app.test_client()
        db.create_all()
        user = User(username="******", password="******")
        bucketlist1 = Bucketlist(title="Knowledge Goals",
                                 description="Things to learn",
                                 created_by=1)
        bucketlist2 = Bucketlist(title="Adventures",
                                 description="Awesome adventures to go on",
                                 created_by=1)
        item1 = Item(title="Learn to Cook",
                     description="Cook at least 10 different meals",
                     created_by=1,
                     bucketlist_id=1)
        item2 = Item(title="Swim with Dolphins",
                     description="Go swimming with dolphins in Watamu",
                     created_by=1,
                     bucketlist_id=2)

        db.session.add(user)
        db.session.add(bucketlist1)
        db.session.add(bucketlist2)
        db.session.add(item1)
        db.session.add(item2)
        db.session.commit()
Beispiel #4
0
 def test_find_by_availability(self):
     """ Find a Item by Availability """
     Item(0, "fido", "dog", False).save()
     Item(0, "kitty", "cat", True).save()
     items = Item.find_by_availability(True)
     self.assertEqual(len(items), 1)
     self.assertEqual(items[0].name, "kitty")
Beispiel #5
0
    def test_creating_an_item(self):
        self.assertEqual(self.bucketlist.id, 1)
        self.assertEqual(self.bucketlist.name, "Cook")

        item = Item("Cook lunch", self.bucketlist.id, "Coooking Ugali omena")
        db.session.add(item)
        db.session.commit()

        self.assertEqual(item.name, "Cook lunch")
        self.assertEqual(item.description, "Coooking Ugali omena")
        self.assertEqual(item.done, False)
        year = str(datetime.today().year)
        self.assertIn(year, str(item.date_created))
        self.assertIn(year, str(item.date_modified))

        # test querying items
        item_query = Item.query.all()
        self.assertIn("<Item 'Cook lunch'>", str(item_query))
        self.assertFalse("<Item 'Not in'>" in str(item_query))

        # creating an item with a missing name results in an error

        with self.assertRaises(Exception) as context:

            # Instantiating a bucketlist object
            item = Item()
            # save the object to database
            db.session.add(item)
            db.session.commit()
            print(context.exception)
            self.assertIn(
                ' __init__() missinfffvgrhhnjyg 2 requirmllmkkjnndmfvmdmb, . / xbg., // n, f, ed positional argument name and bucketlist_id',
                context.exceptio)
Beispiel #6
0
 def test_find_or_404(self):
     """ Find an Item by ID """
     Item(sku="ID111",
          count=3,
          price=2.00,
          name="test_item",
          link="test.com",
          brand_name="gucci",
          is_available=True).save()
     test_item = Item(sku="ID222",
                      count=5,
                      price=10.00,
                      name="some_item",
                      link="link.com",
                      brand_name="nike",
                      is_available=False)
     test_item.save()
     item = Item.find_or_404(test_item.id)
     self.assertIsNot(item, None)
     self.assertEqual(item.sku, test_item.sku)
     self.assertEqual(item.count, 5)
     self.assertEqual(item.price, 10.00)
     self.assertEqual(item.name, "some_item")
     self.assertEqual(item.link, "link.com")
     self.assertEqual(item.is_available, False)
    def setUp(self):
        """ Runs before each test """
        server.init_db()
        db.drop_all()  # clean up the last tests
        db.create_all()  # create new tables
        date = datetime.now()

        order = Order(customer_id=1, date=date, status='processing').save()
        order = Order(customer_id=2, date=date, status='processing').save()

        order1 = Order()
        order1 = order1.find_by_customer_id(1)[0]
        order2 = Order()
        order2 = order2.find_by_customer_id(2)[0]

        item = Item(order_id=order1.id,
                    product_id=1,
                    name='hammer',
                    quantity=1,
                    price=11.50).save()
        item = Item(order_id=order1.id,
                    product_id=2,
                    name='toilet paper',
                    quantity=2,
                    price=2.50).save()
        item = Item(order_id=order2.id,
                    product_id=3,
                    name='beer',
                    quantity=2,
                    price=10.50).save()
        self.app = server.app.test_client()
Beispiel #8
0
    def setUp(self):

        # setup the app and push app context:
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

    
        # setup the db:
        db.drop_all()
        db.create_all()

        # create test datas for the users, bucketlists, and items:
        user = User(
            username='******', 
            email='*****@*****.**',
            password='******'
        )
        user.save()


        self.user = User(email="*****@*****.**", password="******", username="******")
        self.user.save()
        
        self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id)
        self.bucket_item.save()

        self.item = Item(name="Item 1", bucketlist_id=self.bucket_item.id)
        self.item.save()

        self.user2 = User(email="*****@*****.**", password="******", username="******")
        self.user2.save()
        self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id)
        self.bucket_item2.save() 

        self.item2 = Item(name="Item 1", bucketlist_id=self.bucket_item2.id)
        self.item2.save()


        bucket_item = Bucketlist(name="Bucket List", user_id=user.id)
        bucket_item.save()


        item = Item(name="Item 1", bucketlist_id=bucket_item.id)
        item.save() 

        self.client = self.app.test_client()


        #create default login 
        login_details = {
    	'email': '*****@*****.**',
    	'password': '******'}
    	response = self.client.post(
    		url_for('api.login'),
            headers=self.get_api_headers(),
            data=json.dumps(login_details)
            )
    	self.token = json.loads(response.data)['token']
Beispiel #9
0
 def test_find_item(self):
     """ Find a Item by id """
     Item(0, "fido", "dog").save()
     Item(0, "kitty", "cat").save()
     item = Item.find(2)
     self.assertIsNot(item, None)
     self.assertEqual(item.id, 2)
     self.assertEqual(item.name, "kitty")
Beispiel #10
0
 def test_find_by_price(self):
     """ Find a Item by Price """
     Item(0, "fido", "dog").save()
     Item(0, "kitty", "cat").save()
     items = Item.find_by_price("cat")
     self.assertNotEqual(len(items), 0)
     self.assertEqual(items[0].price, "cat")
     self.assertEqual(items[0].name, "kitty")
Beispiel #11
0
 def test_for_case_insensitive(self):
     """ Test for Case Insensitive Search """
     Item(0, "Fido", "DOG").save()
     Item(0, "Kitty", "CAT").save()
     items = Item.find_by_name("fido")
     self.assertNotEqual(len(items), 0)
     self.assertEqual(items[0].name, "Fido")
     items = Item.find_by_price("cat")
     self.assertNotEqual(len(items), 0)
     self.assertEqual(items[0].price, "CAT")
Beispiel #12
0
 def test_group_get_items(self):
     category = Category(name='TEST CATEGORY NAME')
     item1 = Item(title='TEST ITEM NAME 1', group_id=1)
     item2 = Item(title='TEST ITEM NAME 2', group_id=1)
     db.session.add(category)
     db.session.add(item1)
     db.session.add(item2)
     db.session.commit()
     self.assertTrue(item1 in category.get_items().all())
     self.assertTrue(item2 in category.get_items().all())
Beispiel #13
0
    async def test_list(self):
        item1 = Item(name='item1')
        await item1.commit()
        item2 = Item(name='item2')
        await item2.commit()

        resp = await self.client.get("/items")
        assert resp.status == 200
        items = await resp.json()
        assert len(items) == 2
Beispiel #14
0
    def setUpClass(cls):
        """ Using glove-wiki as its a much smaller model, so the test will run a
            lot faster than using the default model"""
        cls.model = api.load('glove-wiki-gigaword-50')

        cls.item1_1 = Item(name="test", desc="this a test")
        cls.item2_1 = Item(name="apple", desc="a half eaten apple")
        cls.item2_2 = Item(name="apple iphone", desc="model is iphone 7 plus")
        cls.item2_3 = Item(name="phone", desc="lost my iphone")
        cls.item2_4 = Item(name="missing phone",
                           desc="lost my phone somewhere" +
                           ", is a google pixel")
Beispiel #15
0
    def setUp(self):
        """Create test client and some sample data"""

        self.client = app.test_client()

        u1, u2, u3, s1, s2, f1, droplist, droplist_2, droplist_3 = droplist_setup(
        )

        self.u1 = u1
        self.u2 = u2
        self.u3 = u3
        self.s1 = s1
        self.s2 = s2
        self.f1 = f1
        self.droplist = droplist
        self.droplist_2 = droplist_2

        loc = Location(name="S409")
        loc_2 = Location(name="S408")
        loc_3 = Location(name="113")

        db.session.add_all([loc, loc_2, loc_3])
        db.session.commit()

        self.loc = loc
        self.loc_2 = loc_2
        self.loc_3 = loc_3

        item_1 = Item(row_letter="a",
                      column_number=1,
                      location_id=self.loc.id,
                      description="Test Item 1",
                      droplist_id=self.droplist_2.id)

        item_2 = Item(row_letter="a",
                      column_number=2,
                      location_id=self.loc_2.id,
                      description="Test Item 2",
                      droplist_id=self.droplist_2.id)

        item_3 = Item(row_letter="c",
                      column_number=3,
                      location_id=self.loc_3.id,
                      description="Test Item 3",
                      droplist_id=self.droplist_2.id)

        db.session.add_all([item_1, item_2, item_3])
        db.session.commit()

        self.item_1 = item_1
        self.item_2 = item_2
        self.item_3 = item_3
Beispiel #16
0
def test_new_basket():
    item1 = Item('order-1', 'Macbook Air', 1199.30, 1, 'Electronics')
    item2 = Item('order-2', 'Airpods', 199.20, 1, 'Electronics')
    item3 = Item('order-3', 'Nike Air Max', 128.50, 1, 'Shoes')

    basket = Basket()
    basket.add_to_basket(item1)
    basket.add_to_basket(item2)
    basket.add_to_basket(item3)

    assert len(basket.items) == 3
    assert basket.total == 1527
    assert basket.items[1].name == 'Airpods'
def upload_form():
    form = UploadForm()
    if form.validate_on_submit():
        if not form.pic.data:
            flash('Please select the file')
        else:
            suffix = os.path.splitext(form.pic.data.filename)[1]
            filename = random_string() + suffix
            photos.save(form.pic.data, name=filename)
            category = Category.query.filter_by(
                name=form.category.data).first()
            if form.store_location.data == 'No selection':
                item = Item(item_name=form.item_name.data,
                            status=form.status.data,
                            location=form.location.data,
                            time=form.time.data,
                            category_id=category.id,
                            description=form.description.data,
                            pic=filename,
                            uploader_id=current_user.id)
            else:
                storage = Storage.query.filter_by(
                    location_name=form.store_location.data).first()
                item = Item(item_name=form.item_name.data,
                            status=form.status.data,
                            location=form.location.data,
                            time=form.time.data,
                            category_id=category.id,
                            description=form.description.data,
                            pic=filename,
                            uploader_id=current_user.id,
                            store_location_id=storage.id)
            db.session.add(item)
            item_change = Item.query.filter_by(
                item_name=form.item_name.data,
                time=form.time.data,
                location=form.location.data,
                description=form.description.data).first()
            change = Change(changer_id=current_user.id,
                            method='upload',
                            item_id=item_change.id,
                            item_name=item_change.item_name,
                            content='create a ' + form.status.data +
                            ' item named ' + form.item_name.data)
            db.session.add(change)
            db.session.commit()
            return 'success'
    return render_template('upload_form.html',
                           form=form,
                           current_user=current_user)
Beispiel #18
0
def addItems(app):
    with app.app_context():
        app.logger.info("Adding order items...")

        db.session.add(
            Item(
                name="2021 Badge",
                description="The badge for the 2021 Kohoutek Online event",
                image="2021.png",
                unit_cost=1,
                index=1,
            ))

        db.session.add(
            Item(
                name="2020 Badge",
                description="The 2020 event badge",
                image="2020.png",
                unit_cost=1,
                limited=True,
                stock=100,
                index=2,
            ))

        db.session.add(
            Item(
                name="2019 Badge",
                description="The 2019 event badge",
                image="2019.png",
                unit_cost=1,
                limited=True,
                stock=150,
                index=3,
            ))

        db.session.add(
            Item(
                name="UOBGAS Badge",
                description=
                "The 'UOBGAS' (University of Bristol Guides and Scouts) club badge",
                image="uobgas.png",
                unit_cost=1,
                limited=True,
                stock=30,
                index=4,
            ))

        db.session.commit()
        app.logger.info("...done!")
Beispiel #19
0
def create_items():
    """
    Creates a Item
    This endpoint will create a Item based the data in the body that is posted
    """
    data = {}
    # Check for form submission data
    if request.headers.get(
            'Content-Type') == 'application/x-www-form-urlencoded':
        app.logger.info('Getting data from form submit')
        data = {
            'name': request.form['name'],
            'price': request.form['price'],
            'available': True
        }
    else:
        app.logger.info('Getting data from API call')
        data = request.get_json()
    app.logger.info(data)
    item = Item()
    item.deserialize(data)
    item.save()
    message = item.serialize()
    location_url = url_for('get_items', item_id=item.id, _external=True)
    return make_response(jsonify(message), status.HTTP_201_CREATED,
                         {'Location': location_url})
Beispiel #20
0
 def add_suite(self, vendor_id):
     suite = Item(
         vendor_id=vendor_id,
         item=self.item.data,
         price=self.price.data,
         second_material_id=self.second_material_id.data,
         category_id=0,
         scene_id=self.scene_id.data,
         length='',
         width='',
         height='',
         area=self.area.data,
         stove_id=self.stove_id.data,
         outside_sand_id=self.outside_sand_id.data,
         inside_sand_id=self.inside_sand_id.data,
         paint_id=0,
         decoration_id=0,
         style_id=self.style_id.data,
         carve_type_id=self.carve_type_id.data,
         story=self.story.data,
         suite_id=0,
         amount=1,
         is_suite=True,
         is_component=False
     )
     db.session.add(suite)
     db.session.commit()
     statisitc.init_statistic()
     return suite
Beispiel #21
0
 def add_component(self, vendor_id, suite_id):
     component = Item(
         vendor_id=vendor_id,
         item=self.component.data,
         price=0,
         second_material_id=0,
         category_id=self.category_id.data,
         scene_id=0,
         length=self.length.data,
         width=self.width.data,
         height=self.height.data,
         area=self.area.data,
         stove_id=0,
         outside_sand_id=0,
         inside_sand_id=0,
         paint_id=self.paint_id.data,
         decoration_id=self.decoration_id.data,
         style_id=0,
         carve_type_id=0,
         story='',
         suite_id=suite_id,
         amount=self.amount.data,
         is_suite=False,
         is_component=True
     )
     db.session.add(component)
     db.session.commit()
     self.add_attach(component.id)
     return component
Beispiel #22
0
 def add_item(self, vendor_id):
     item = Item(
         vendor_id=vendor_id,
         item=self.item.data,
         price=self.price.data,
         second_material_id=self.second_material_id.data,
         category_id=self.category_id.data,
         scene_id=self.scene_id.data,
         length=self.length.data,
         width=self.width.data,
         height=self.height.data,
         area=self.area.data,
         stove_id=self.stove_id.data,
         outside_sand_id=self.outside_sand_id.data,
         inside_sand_id=self.inside_sand_id.data if self.inside_sand_id.data else 0,
         paint_id=self.paint_id.data,
         decoration_id=self.decoration_id.data,
         style_id=self.style_id.data,
         carve_type_id=self.carve_type_id.data,
         story=self.story.data,
         suite_id=0,
         amount=1,
         is_suite=False,
         is_component=False
     )
     db.session.add(item)
     db.session.commit()
     self.add_attach(item.id)
     statisitc.init_statistic()
     return item
Beispiel #23
0
def add_item(user_id):
    user = db.session.query(User).filter_by(id=user_id).first()
    tokens = map(lambda x: x.token, user.tokens)
    check = check_auth_header(request.headers)
    if not check[0]:
        return check[1]
    if not authenticate_user(tokens, request.headers['AuthToken']):
        return unauthorized_message()

    data = MultiDict(mapping=request.json)
    inputs = ItemForm(data, csrf_enabled=False)
    if not inputs.validate():
        return bad_request_error(inputs.errors)

    data = request.get_json()
    name = data['name']
    description = data['description']
    thumbnail_url = data['thumbnail_url']
    item_url = data['item_url']
    item = Item(name, description, thumbnail_url, user_id, item_url)
    db.session.add(item)
    db.session.commit()
    response = jsonify({
        'name': item.name,
        'description': item.description,
        'thumbnail_url': item.thumbnail_url
    })
    response.status_code = 201
    return response
Beispiel #24
0
def item_init(dic):
    i = 0
    catz = []
    for key in dic['name']:
        seller = Seller.query.filter_by(
            username=dic['merchant_id'][key]).first()
        cat = dic['amazon_category_and_sub_category'][key]
        if pd.isna(cat) is True:
            cat = 'Other'
        else:
            cats = cat.split(' > ')
            cat = cats[0]

            if cat not in catz:
                toAdd = Category(name=cat)
                db.session.add(toAdd)
                catz.append(cat)
        if not seller:
            toAdd = Seller(username=str(dic['merchant_id'][key]),
                           email=str(dic['merchant_id'][key]) + str(i) +
                           "@NULL")
            i += 1
            toAdd.set_password('123')
            db.session.add(toAdd)
        item = Item(id=key,
                    name=dic['name'][key],
                    price=dic['price'][key],
                    quantity=dic['quantity'][key],
                    description=dic['description'][key],
                    seller=Seller.query.filter_by(
                        username=dic['merchant_id'][key]).first(),
                    category=cat)
        date = '' + str(datetime.now().month) + '/' + str(
            datetime.now().day) + '/' + str(datetime.now().year)
        location = ['USA', 'Canada', 'United Kingdom', 'China', 'Japan']
        stars = [1, 2, 3, 4, 5]
        user_id = []
        for user in User.query.all():
            user_id.append(user.id)
        for i in range(5):
            review = Reviews(user_id=random.choice(user_id),
                             item_id=item.id,
                             date_time=date,
                             location=random.choice(location),
                             stars=random.choice(stars),
                             content=get_random_string(10))
            db.session.add(review)
        avg_stars = db.session.query(func.avg(
            Reviews.stars)).filter(Reviews.item_id == item.id).first()
        item.avg_user_rating = avg_stars[0]
        db.session.add(item)
    #for name in catz:
    #_search_params = {
    #'q': name,
    #'num': 1,
    #"print_urls":True
    #}
    #print(name)
    #gis.search(search_params=_search_params, path_to_dir='Images', width=500, height=500, custom_image_name=str(name))
    db.session.commit()
Beispiel #25
0
 def test_decode_item_token(self):
     item = Item(name='Test')
     db.session.add(item)
     db.session.commit()
     token = item.generate_item_token('Tester')
     self.assertTrue(isinstance(token, bytes))
     self.assertFalse(Item.decode_item_token(token) == None, None)
Beispiel #26
0
    def form_valid(self, form):
        data = form.cleaned_data
        requeriment = Requirement.objects.get(id=self.kwargs['requeriment_id'])
        requeriment.name = data['name_item']
        requeriment.description = data['description']
        common_user = self.object.commonuser
        common_user.cpf = data['cpf']
        common_user.phone = data['phone']
        common_user.anonymous = data['anonymous']
        common_user.save()
        new_item = Item(owner=self.request.user,
                        description=requeriment.description,
                        name_item=requeriment.name)
        new_item.save()
        new_object = Object(item=new_item, type=requeriment.type)
        new_object.save()
        messages.success(self.request, "Novo Objeto cadastrado com sucesso!")
        match = Match(requirement=requeriment, item=new_item)
        match.save()
        notification = Notification(user=requeriment.owner, match=match)
        notification.save()
        donation = Donation(
            donator=self.request.user,
            institute=requeriment.owner,
            item=new_item,
            data=datetime.datetime.today().strftime('%Y-%m-%d'),
            is_completed=False)
        donation.save()
        messages.success(self.request, 'Muito Obrigado pela sua Doação!')

        return super(DonatorRequerimentView, self).form_valid(form)
Beispiel #27
0
 def setUp(self):
     super().setUp()
     category = Category(name='test_category')
     item = Item(name='test_item')
     item.category = category
     db.session.add(item)
     db.session.commit()
Beispiel #28
0
def shopping_list():

    if request.method == "POST":
        print("Posted Data")
        post_data = request.get_json()
        item = Item(item=post_data.get('item'),
                    quantity=post_data.get('quantity'),
                    status=post_data.get('bought'))
        db.session.add(item)
        db.session.commit()
        return jsonify("Item Added")

    if request.method == "GET":
        all_items = Item.query.all()

        # use the AlchemyEncoder helper class to encode the query object in to JSON
        output = json.dumps(all_items, cls=AlchemyEncoder)
        output = json.loads(output)

        return jsonify({"list": output, 'status': 'success'})

    if request.method == 'DELETE':
        Item.query.delete()
        db.session.commit()
        return jsonify("All Deleted")
Beispiel #29
0
 def test_item_model(self):
     item = Item({
         'name': "name",
         'icon': "fakeicon.png",
         'examine_info': "fake info",
         'type': "fake type",
         'market_price': 99,
         'weight': 0,
         'members_only': True,
         'equipable': True,
         'quest_item': False
     })
     db.session.add(item)
     db.session.commit()
     items = Item.query.all()
     assert item in items
     assert str(item) == "<Item 'name'>"
     assert item.toJSON(False) == {
         'id': 1,
         'name': 'name',
         'icon': "fakeicon.png",
         'examine_info': "fake info",
         'item_type': "fake type",
         'market_price': 99,
         'weight': 0
     }
     assert len(items) == 1
Beispiel #30
0
 def test_serialize_an_item(self):
     """ Test serialization of an Item """
     item = Item(sku="ID111",
                 count=3,
                 price=2.00,
                 name="test_item",
                 link="test.com",
                 brand_name="gucci",
                 is_available=True)
     data = item.serialize()
     self.assertNotEqual(data, None)
     self.assertIn('id', data)
     self.assertEqual(data['id'], None)
     self.assertIn('sku', data)
     self.assertEqual(data['sku'], "ID111")
     self.assertIn('count', data)
     self.assertEqual(data['count'], 3)
     self.assertIn('price', data)
     self.assertEqual(data['price'], 2.00)
     self.assertIn('name', data)
     self.assertEqual(data['name'], "test_item")
     self.assertIn('link', data)
     self.assertEqual(data['link'], "test.com")
     self.assertIn('brand_name', data)
     self.assertEqual(data['brand_name'], "gucci")
     self.assertIn('is_available', data)
     self.assertEqual(data['is_available'], True)