如何使用YAML,tavern和pytest使用基本身份验证来测试API

时间:2019-03-14 07:53:07

标签: python-3.x yaml pytest tavern

我正在实现Delete API,该API需要在删除任何用户之前进行基本身份验证。以下是我用于基本身份验证和删除用户的代码,该代码可以通过curl命令正常运行。

def auth_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if(request.authorization != None and request.authorization["username"] != None and request.authorization["password"] != None):
            username = request.authorization["username"]
            password = request.authorization["password"]
        else:
            return make_response('User does not exists.\n' 'Please provide user credentials', 401,
                    {'WWW-Authenticate': 'Basic realm="Login Required"'})
        if check_auth(username, password):
            return f(*args, **kwargs)
        else:
            return  make_response('Could not verify the credentials.\n' 'Please use correct credentials', 401,
                    {'WWW-Authenticate': 'Basic realm="Login Required"'})
    return decorated

def check_auth(username, password):
    cur = get_db().cursor().execute("SELECT user_name, password from users WHERE user_name=?", (username,))
    row = cur.fetchone()
    if row and row[0] == username and pbkdf2_sha256.verify(password, row[1]):
        return True
    else:
        return False

#curl command to execure delete function - curl -u parag:parag --include --verbose --request DELETE --header 'Content-Type: application/json' http://localhost:5000/delete_user/
@app.route('/delete_user', methods=['DELETE'])
@auth_required
def api_delete_user():
        if request.method == 'DELETE':
            status_code:bool = False
        cur = get_db().cursor()
        username = request.authorization["username"]
        try:
            cur.execute("UPDATE users SET active_status =? WHERE user_name=?",(0, username,))
            if(cur.rowcount >= 1):
                get_db().commit()
                status_code = True
        except:
            get_db().rollback()
            status_code = False
        finally:
            if status_code:
                return jsonify(message="Passed"), 201
            else:
                return jsonify(message="Fail"), 409

我已经创建了一个YAML文件来测试上述删除API,但无法在其中添加基本身份验证。以下是我用于测试删除API的YAML文件。

test_name: Delete existing user

stages:
  - name: Make sure you delete existing user
    request:
      url: http://localhost:5000/delete_user
      json:

      method: DELETE
      headers:
        content-type: application/json
    response:
      status_code: 201
      body:
        message: Passed
      save:
        $ext:
          context:
            parameters:
              auth_required:
                username: parag
                password: bhingre

以上文件并不能帮助我在删除用户之前通过基本身份验证来删除用户。 请让我知道是否有解决方案或建议。

1 个答案:

答案 0 :(得分:0)

尝试在标题中添加授权,并从标题中读取授权值。 它对我有用。

headers:
  content-type: application/json
  Authorization: "Basic trydtfjgbyugvyujbbyy"