Httpunner HTTPBasicAuth加密
# 第一種方式 auth_token = None def getToken(loginURL, login_client, login_client_pwd, login_user, login_pwd, login_grt_type): ''' 獲取token, 預留 :param accessToken: :return: ''' global auth_token if not auth_token: loginURL = loginURL.strip('/') auth = HTTPBasicAuth(login_client, login_client_pwd) data_value = {'username': login_user, 'password': login_pwd, 'grant_type': login_grt_type} url = loginURL + '/api/token' res = requests.request('POST', url, data = data_value, auth=auth) response = res.json() auth_token = 'Bearer ' + str(response.get('access_token')) return auth_token
config: name: 管理 base_url: '' variables: Authorization: ${getToken($oauthURL, $login_client, $login_client_pwd, $login_user, $login_pwd, $login_grt_type)} teardown_hooks: []
# 第二種方式 def set_hook_basic_auth(request, client, client_pwd): ''' basicAuth 用戶及密碼 加密 :param request: :param client: :param client_pwd: :return: ''' request['auth'] = HTTPBasicAuth(client, client_pwd) def alter_response(res): ''' 獲取token :param accessToken: :return: ''' if res.json.get('access_token'): res.json['access_token'] = "Bearer " + res.json.get('access_token') - name: 登錄 api: api/登錄/登錄.yaml variables: username: 'admin' password: '123456' grant_type: 'password' validate: [] setup_hooks: - ${set_hook_basic_auth($request, client, 123456)} output: - accessToken: content.access_token
# 第三種 from requests.auth import HTTPBasicAuth import requests def getToken(loginURL, login_client, login_client_pwd, login_user, login_pwd, login_grt_type): ''' 獲取token, 預留 :param accessToken: :return: ''' global auth_token if not auth_token: loginURL = loginURL.strip('/') auth = HTTPBasicAuth(login_client, login_client_pwd) data_value = {'username': login_user, 'password': login_pwd, 'grant_type': login_grt_type} url = loginURL + '/api/token' res = requests.request('POST', url, data = data_value, auth=auth) response = res.json() auth_token = 'Bearer ' + str(response.get('access_token')) return auth_token testsuites: config: name: 測試API base_url: '' variables: login_client: 'client' login_client_pwd: 'pwd1' login_user: 'user' login_pwd: 'pwd2' login_grt_type: 'password' Authorization: ${getToken($oauthURL, $login_client, $login_client_pwd, $login_user, $login_pwd, $login_grt_type)}