Ejemplo n.º 1
0
def create_random():
    #LOG = log.getLogger(__name__)
    version = request.headers.get('X-Version', '1.0')
    req = request.json
    ver = str(version.decode('utf8'))

    LOG.debug("req: %s, version : %s" % (req, ver))
    ver_req = version_obj.version_obj(req, ver)

    try:
        validation.validate(ver_req, validation.create_random)

        length = req.get('length')
        timeout = req.get('time_out', 10)
        if ver_req == version_obj.version_obj('', '1.0'):
            ret = random_manager.create_random(length, timeout=timeout)
        elif ver_req > version_obj.version_obj('', '1.0'):
            ret = {}
        else:
            ret = {}

    except (exceptions.inValidateInput,
            exceptions.VersionNotSupport) as e:
        LOG.error(e)
        return error_json_out(400, e.message)
    except exceptions.CodeCreateFailed as e:
        LOG.error(e)
        return error_json_out(403, e.message)
    LOG.debug("ret=%s" % ret)
    return jsonify(ret), 201
def test_validate_custom_dictionary_bad_file():
    # Arrange
    filename = TEST_FILE_DIR / 'example_ags.ags'
    dictionary = 'bad_file.ags'

    # Act
    with pytest.raises(ValueError) as err:
        validation.validate(filename, standard_AGS4_dictionary=dictionary)

    # Assert
    message = str(err.value)
    assert 'dictionary' in message
    for key in validation.STANDARD_DICTIONARIES:
        assert key in message
def test_validate_non_ags():
    # Arrange
    filename = TEST_FILE_DIR / 'bad.extension'
    expected = {
        'checkers': [],
        'dictionary': '',
        'errors': {
            'File read error': [{
                'desc': 'bad.extension is not an .ags file',
                'group': '',
                'line': '-'
            }]
        },
        'filename': 'bad.extension',
        'filesize': 0,
        'message': '1 error(s) found in file!',
        'time': dt.datetime(2021, 8, 23, 14, 25, 43, tzinfo=dt.timezone.utc),
        'valid': False,
        'additional_metadata': {}
    }

    # Act
    response = validation.validate(filename)

    # Assert
    assert response == expected
Ejemplo n.º 4
0
def accept(key):
    """Creates report from document using key specified."""
    doc = db["document/" + key]
    is_valid = validate(doc["report"])["isValid"] is True

    if is_valid:
        doc["status"] = "accepted"
        db.save(doc)
        __save_report(key, doc)

    return jsonify({"status": is_valid})
Ejemplo n.º 5
0
def validate_doc(key):
    """Validates document."""
    j = request.get_json(force=True)
    d = db["document/" + key]

    d["location"] = j["location"]
    d["event"] = j["event"]
    d["report"] = j["report"]
    status = validate(d["report"])

    return jsonify(status)
def test_validate_custom_dictionary(dictionary):
    # Arrange
    filename = TEST_FILE_DIR / 'example_ags.ags'

    # Act
    response = validation.validate(filename,
                                   standard_AGS4_dictionary=dictionary)

    # Assert
    assert response['filename'] == 'example_ags.ags'
    assert response['dictionary'] == dictionary
Ejemplo n.º 7
0
def accept():
    """Accepts document been sent by client."""
    key = "document/" + uuid.uuid4().hex  # generate new id for document

    data = request.get_json(force=True)
    data["_id"] = key  # save document with generated key
    data["created"] = date.today().strftime("%Y/%m/%d")
    data["validation"] = validate(data["report"])  # save validation data too
    data["status"] = "valid" if data["validation"]["isValid"] else "invalid"
    db.save(data)

    return jsonify({"status": "ok"})
def test_validate(filename, expected):
    # Arrange
    filename = TEST_FILE_DIR / filename

    # Act
    response = validation.validate(filename)

    # Assert
    # Check that metadata fields are correct
    for key in [
            'filename', 'filesize', 'checkers', 'time', 'dictionary', 'errors',
            'message', 'valid', 'additional_metadata'
    ]:
        assert response[key] == expected[key]
Ejemplo n.º 9
0
def save(key):
    """Saves changes."""
    j = request.get_json(force=True)
    d = db["document/" + key]

    d["location"] = j["location"]
    d["event"] = j["event"]
    d["report"] = j["report"]

    status = validate(d["report"])
    d["validation"] = status
    d["status"] = "valid" if status["isValid"] else "invalid"
    db.save(d)

    return jsonify(status)
Ejemplo n.º 10
0
    def post(self):

        user = flask_restful.request.get_json()

        is_valid, errors = validate(user, schema='auth')

        if not is_valid:
            resp = jsonify(errors)
            resp.status_code = 400
            return resp

        result = verify(**user)

        if result:
            token = create_access_token(identity=result.id)

            return {'access_token': token}, 200

        return {'msg': 'Login or password invalid'}, 401
def test_validate_default_checker():
    """Simulate a valid file with AGS checker"""
    # Arrange
    filename = TEST_FILE_DIR / 'does_not_matter.ags'
    expected = {
        'checkers': ['ags'],
        'dictionary': 'some_dict',
        'errors': {},
        'filename': filename.name,
        'filesize': 0,
        'message': 'All checks passed!',
        'time': dt.datetime(2021, 8, 23, 14, 25, 43, tzinfo=dt.timezone.utc),
        'valid': True,
        'additional_metadata': {}
    }

    # Act
    response = validation.validate(filename, checkers=[mock_check_ags])

    # Assert
    assert response == expected
def test_validate_bgs_checker():
    """Simulate a failing file with BGS checker."""
    # Arrange
    filename = TEST_FILE_DIR / 'does_not_matter.ags'
    expected = {
        'checkers': ['bgs'],
        'dictionary': '',
        'errors': {
            'BGS': [{}]
        },
        'filename': filename.name,
        'filesize': 0,
        'message': '1 error(s) found in file!',
        'time': dt.datetime(2021, 8, 23, 14, 25, 43, tzinfo=dt.timezone.utc),
        'valid': False,
        'additional_metadata': {}
    }

    # Act
    response = validation.validate(filename, checkers=[mock_check_bgs])

    # Assert
    assert response == expected