Beispiel #1
0
def test_min():
    field = NumberParameters.from_json_field('test', True, {
        "type": "number",
        "minimum": 2.99,
        "default": 5.0
    })
    constraints = field.get_options()
    hamcrest.assert_that(
        constraints,
        hamcrest.has_entries({
            'validators':
            hamcrest.contains_exactly(
                hamcrest.instance_of(wtforms.validators.DataRequired),
                hamcrest.instance_of(
                    jsonschema_wtforms.validators.NumberRange))
        }))
    assert field.required is True
    assert field.attributes['default']
    assert field.get_factory() == wtforms.fields.FloatField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 2.10})
    assert form.validate() is False
    assert form.errors == {'test': ['Number must be at least 2.99.']}

    form.process(data={'test': 12})
    assert form.validate() is True
    assert not form.errors
Beispiel #2
0
def test_max():
    field = NumberParameters.from_json_field('test', True, {
        "type": "integer",
        "maximum": 20
    })

    constraints = field.get_options()
    hamcrest.assert_that(
        constraints,
        hamcrest.has_entries({
            'validators':
            hamcrest.contains_exactly(
                hamcrest.instance_of(wtforms.validators.DataRequired),
                hamcrest.instance_of(
                    jsonschema_wtforms.validators.NumberRange))
        }))

    assert field.required is True
    assert field.get_factory() == wtforms.fields.IntegerField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 21})
    assert form.validate() is False
    assert form.errors == {'test': ['Number must be at most 20.']}

    form.process(data={'test': 12})
    assert form.validate() is True
    assert not form.errors
Beispiel #3
0
def test_length():
    field = StringParameters.from_json_field('test', True, {
        "type": "string",
        "minLength": 1,
        "maxLength": 5
    })

    constraints = field.get_options()
    hamcrest.assert_that(constraints, hamcrest.has_entries({
        'validators': hamcrest.contains_exactly(
            hamcrest.instance_of(wtforms.validators.DataRequired),
            hamcrest.instance_of(wtforms.validators.Length)
        ),
    }))

    assert field.required is True
    assert field.get_factory() == wtforms.fields.StringField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 'administrator'})
    assert form.validate() is False
    assert form.errors == {'test': [
        'Field must be between 1 and 5 characters long.'
    ]}

    form.process(data={'test': 'admin'})
    assert form.validate() is True
    assert not form.errors
Beispiel #4
0
def test_enum():
    field = NumberParameters.from_json_field('test', True, {
        "type": "integer",
        "enum": [1, 2]
    })

    constraints = field.get_options()
    hamcrest.assert_that(
        constraints,
        hamcrest.has_entries({
            'validators':
            hamcrest.contains_exactly(
                hamcrest.instance_of(wtforms.validators.DataRequired), ),
        }))

    assert field.required is True
    assert field.get_factory() == wtforms.fields.SelectField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 9})
    assert form.validate() is False
    assert form.errors == {'test': ['Not a valid choice.']}

    form.process(data={'test': 1})
    assert form.validate() is True
    assert not form.errors
Beispiel #5
0
def test_complex_array():

    field = ArrayParameters.from_json_field(
        'test', True, {
            "type": "array",
            "default": [[1]],
            "items": {
                "type": "array",
                "items": {
                    "type": "number"
                }
            }
        })

    form = wtforms.form.BaseForm({"test": field()})
    form.process()
    assert form._fields['test'].data == field.attributes['default']
    assert form.validate()

    factory = field.get_factory()
    assert factory.func == wtforms.fields.FieldList
    subfield = factory.args[0].field_class
    assert subfield == wtforms.fields.FieldList
    subsubfield = factory.args[0].args[0].field_class
    assert subsubfield == wtforms.fields.FloatField
Beispiel #6
0
def test_password_format():
    field = StringParameters.from_json_field('test', True, {
        "title": "Password",
        "type": "string",
        "writeOnly": True,
        "format": "password"
    })
    assert field.get_factory() == wtforms.fields.PasswordField
    form = wtforms.form.BaseForm({"test": field()})
    form.process()
    assert form._fields['test']() == (
        '<input id="test" '
        'name="test" required type="password" value="">'
    )
Beispiel #7
0
def test_uri_format():
    field = StringParameters.from_json_field('test', True, {
        "minLength": 1,
        "maxLength": 2083,
        "format": "uri",
        "type": "string"
    })
    assert field.get_factory() == wtforms.fields.URLField
    form = wtforms.form.BaseForm({"test": field()})
    form.process()
    assert form._fields['test']() == (
        '<input id="test" maxlength="2083" minlength="1" '
        'name="test" required type="url" value="">'
    )
Beispiel #8
0
def test_array_length():

    field = ArrayParameters.from_json_field('test', True, {
        "type": "array",
        "minItems": 2,
        "maxItems": 3,
        "items": {
            "type": "number"
        }
    })

    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': [1, 2, 3]})
    assert form.validate() is True
    assert not form.errors

    # Fixme, this sucks.
    # It probably needs a formdata, to work properly
    with pytest.raises(AssertionError):
        form.process(data={'test': [1, 4, 5, 9]})
Beispiel #9
0
def delete_category():
    """
    End point to delete an empty category from catalog
    :return: back to home page
    """
    if login_session.get("email") is not None:
        category_count_list = get_empty_category_counts()
        form = Delete_Category(request.form)

        if request.method == "POST":
            for datum in form.categories.data:
                print datum
                category_to_delete = db.session.query(Categories).filter_by(category_id=datum).first()
                db.session.delete(category_to_delete)
                db.session.commit()

            return redirect(url_for("index"))
        else:
            form.categories.choices = category_count_list
            form.process()
            return render_template("pages/delete-category.html", form=form)
Beispiel #10
0
def test_boolean():
    field = BooleanParameters.from_json_field('test', True, {
        "type": "boolean",
        "default": "true"
    })

    constraints = field.get_options()
    hamcrest.assert_that(
        constraints,
        hamcrest.has_entries({
            'validators':
            hamcrest.contains_exactly(
                hamcrest.instance_of(wtforms.validators.DataRequired), )
        }))

    assert field.required is True
    assert field.attributes['default']
    assert field.get_factory() == wtforms.fields.BooleanField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 1})
    assert form.validate() is True
Beispiel #11
0
def test_pattern():
    field = StringParameters.from_json_field('test', True, {
        "type": "string",
        "pattern": "^The",
        "default": "The "
    })

    constraints = field.get_options()
    hamcrest.assert_that(constraints, hamcrest.has_entries({
        'validators': hamcrest.contains_exactly(
            hamcrest.instance_of(wtforms.validators.DataRequired),
            hamcrest.instance_of(wtforms.validators.Regexp)
        ),
    }))

    assert field.required is True
    assert field.attributes['default']
    assert field.get_factory() == wtforms.fields.StringField
    form = wtforms.form.BaseForm({"test": field()})
    form.process(data={'test': 'Dagger'})
    assert form.validate() is False
    assert form.errors == {'test': ['Invalid input.']}

    form.process(data={'test': 'The dagger'})
    assert form.validate() is True
    assert not form.errors
    form.process()
    assert form._fields['test']() == (
        '<input id="test" name="test" required type="text" value="The ">'
    )
Beispiel #12
0
def add_item():
    """
    Adds new item to database.  Category is on request object.
    :return:
    """
    if login_session.get("email") is not None:
        form = Catalog_Item(request.form)

        owner = db.session.query(Owners).filter_by(email=login_session.get("email")).first()

        form.category_select.choices = get_all_categories()

        if request.method == "POST" and form.validate():
            # add data

            # get the category object
            cate_number = form.category_select.data
            category = db.session.query(Categories).filter_by(category_id=cate_number).one()

            # category = db.session.query(Categories).first()

            # create a new Item
            item = Items(item_name=form.name.data, owner=owner, category=category)

            # add the description
            item.description = form.description.data

            # add the filename to the database and upload the file
            # need to validate the file name
            if request.files["picture"].filename != "":

                filename = request.files["picture"].filename
                filename = secure_filename(filename)

                # returns a UUID with the file extension
                filename = ensure_unique_filename(filename)

                # builds a URL to put in the database
                item.picture = url_for("static", filename="images/" + filename)

                # read the data and write to a file
                image_data = request.files["picture"].read()
                open(os.path.join(os.path.dirname(__file__), "static/images/", filename), "w").write(image_data)

            # add the item and commit to db
            db.session.add(item)
            db.session.commit()

            # build a url for redirection.  Goes back to the same category the
            # item was added in.
            url_string = "/category/%s" % item.category.category_name
            return redirect(url_string)
        else:
            form.category_id.data = request.args.get("category")

            form.category_select.default = request.args.get("category")
            form.process()  # this sets the default in the select but clears the rest of the form.

            form.id.data = owner.id
            form.category_select.choices = get_all_categories()
            form.submit.label.text = "Add Item"
        return render_template("pages/add-item.html", form=form)
Beispiel #13
0
def edit_item():
    """
    Endpoint to edit an item in the catalog
    :return: returns back to category list
    """
    if login_session.get("email") is not None:
        form = Catalog_Item(request.form)

        if request.method == "POST":
            # delete item
            item = db.session.query(Items).filter_by(id=form.id.data).first()

            cate_number = form.category_select.data
            category = db.session.query(Categories).filter_by(category_id=cate_number).one()

            item.item_name = form.name.data
            item.description = form.description.data
            item.insert_date = datetime.datetime.now()
            item.category = category

            if request.files["picture"].filename != "":
                # delete file if one exists
                try:
                    if os.path.basename(item.picture) != u"default_item.png":
                        os.remove(
                            os.path.join(os.path.dirname(__file__), "static/images/", os.path.basename(item.picture))
                        )
                except OSError:
                    pass

                filename = request.files["picture"].filename
                filename = secure_filename(filename)

                # returns a UUID with the file extension
                filename = ensure_unique_filename(filename)

                # builds a URL to put in the database
                item.picture = url_for("static", filename="images/" + filename)

                # read the data and write to a file
                image_data = request.files["picture"].read()
                open(os.path.join(os.path.dirname(__file__), "static/images/", filename), "w").write(image_data)

            db.session.add(item)
            db.session.commit()
            url_string = "/category/%s" % item.category.category_name
            return redirect(url_string)
        else:
            item = db.session.query(Items).filter_by(id=request.args.get("item_id")).first()
            heading = "Edit Item"
            form.category_select.choices = get_all_categories()
            form.category_select.default = item.category_id
            form.process()  # this sets the default in the select but clears the rest of the form.
            form.name.data = item.item_name
            form.description.data = item.description
            form.picture.data = item.picture
            form.id.data = request.args.get("item_id")
            form.category_id = item.category_id

            form.submit.label.text = "Save Changes"
            # form.process()
            return render_template("pages/edit-item.html", form=form, heading=heading)
Beispiel #14
0
def test_ref_object():
    root_field = ObjectParameters.from_json_field(
        'test', True, {
            "type": "object",
            "properties": {
                "name": {
                    "title": "Name",
                    "type": "string"
                },
                "address": {
                    "$ref": "#/definitions/Address"
                },
                "devices": {
                    "title": "Devices",
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/Device"
                    }
                }
            },
            "required": [
                "name",
            ],
            "definitions": {
                "Address": {
                    "title": "Address",
                    "type": "object",
                    "properties": {
                        "street": {
                            "title": "Street",
                            "type": "string"
                        },
                        "city": {
                            "title": "City",
                            "type": "string"
                        },
                        "phone": {
                            "title": "Phone",
                            "type": "string"
                        }
                    },
                    "required": ["street", "city", "phone"]
                },
                "Device": {
                    "title": "Device",
                    "type": "object",
                    "properties": {
                        "kind": {
                            "title": "Kind",
                            "enum": ["PC", "Laptop"],
                            "type": "string"
                        }
                    },
                    "required": ["kind"]
                }
            }
        })
    assert root_field.label == 'test'
    assert not root_field.description
    addr = root_field.fields['address']
    assert addr.label == 'Address'
    assert not addr.required

    form = wtforms.form.BaseForm({"address": addr()})
    form.process(data={'address': ''})
    assert not form.validate()
    assert form.errors == {
        'address': {
            'city': ['This field is required.'],
            'phone': ['This field is required.'],
            'street': ['This field is required.'],
        }
    }
    form.process(
        data={'address': {
            'city': 'Boppelsen',
            'phone': '666',
            'street': 'A'
        }})
    assert form.validate()

    devices = root_field.fields['devices']
    assert devices.label == 'Devices'
    assert devices.name == 'devices'
    assert not devices.required