RF REST 인터페이스 테스트 사용자 정의 방법

8546 단어 Testing
1, 사용자 정의 인터페이스 json
{
  "url": "http:xxxxxxxxxx",
  "method": "POST",
  "body": {
    "username": "name",
    "password": "pwd"
  }
}

2, 요청 처리 방법 클래스
주: 다음 방법 은 주로 update 와 delete 방법 에서 url 을 수정 한 다음 요청 을 보 내 고 나머지 post 와 get 은 requrl 방법 에 관심 을 가 져 달라 고 요청 하면 됩 니 다.
# coding = utf-8
import pytesseract
from PIL import Image
from selenium import webdriver
import selenium
import time
import json
import requests


class Base_login():
    headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          }

    def __init__(self):
        pass

    # def mark(self, f):
    #     def warpars(**kwargs):
    #         print('%s is start!'.center(100, '=') % f)
    #         f()
    #         print('%s is end!'.center(100, '=') % f)
    #         return f()
    #     return warpars()

    def check_login(self, url, username, passwd, img_dir='D:\payimg'):
        '''
        :param url:
        :param username:
        :param passwd:
        :param img_dir:
        :return: jesssid  token
        '''
        i = 1
        while i < 4:
            driver = webdriver.Chrome()
            driver.set_window_size(1200, 900)
            time.sleep(2)
            driver.get(url)
            time.sleep(1)
            # save image to img_dir
            driver.get_screenshot_as_file(img_dir + '\\checkcode.png')
            # transfer checkcode
            img = Image.open(img_dir + '\\checkcode.png')
            # box = (836, 368, 939, 402)
            box = (765, 315, 855, 345)
            codeshot = img.crop(box)
            codeshot.save(img_dir + '\\code.png')
            checkcode = pytesseract.image_to_string(codeshot).replace(" ", "")
            print('The checkcode is:', checkcode)
            # input login info
            driver.find_element_by_xpath('//*[@id="loginAccount"]').send_keys(username)
            driver.find_element_by_xpath('//*[@id="password"]').send_keys(passwd)
            driver.find_element_by_xpath('//*[@id="randCode"]').send_keys(checkcode)
            driver.find_element_by_xpath('//*[@id="btn_login"]').click()
            time.sleep(6)
            try:
                driver.find_element_by_xpath('//*[@id="page-wrapper"]/div[1]/nav/div/a')
                break
            except selenium.common.exceptions.NoSuchElementException:
                print('failed to catch checkcode %s' % i)
                driver.quit()
            i = i + 1
        cookieL = driver.get_cookies()
        htmlS = driver.page_source
        print(cookieL)
        tokenp = htmlS.split('
')[2].strip(' ') print(tokenp) assert len(tokenp) > 1, 'Get token failed' token = tokenp.split(' ')[2].split('=')[1].strip('\"') print('====%s====' % token) session = cookieL[0].setdefault('value') print(session) driver.quit() return session, token def set_header(self, jessionid, token=''): """ Prepar the request headers for request :param jessionid: session :param token: token :return: headers """ cook = 'JSESSIONID=' + jessionid Base_login.headers['Cookie'] = cook Base_login.headers['X-CSRF-TOKEN'] = token header = Base_login.headers print('The request headers is:', header) return header def set_params(self, jsonf, **kwargs): """ load jsonf and return data dict :param jsonf: json file :param kwargs: need to modify params :return: data dict """ with open(jsonf, 'r') as jp: jdata = json.loads(jp.read()) print('data is:', jdata) data = jdata["body"] print(kwargs) if len(kwargs) != 0: for wrg in kwargs: assert wrg in data, 'Params error! do not in json file!' data[wrg] = kwargs[wrg] print('new data is:', jdata) return jdata def reqUrl(self, jsonf, jessionid, token='', **kw): """ Useage: The common request method ,it can be used for send all post and get request! :param jsonf: json file :param jessionid: sessionid :param token: token :return: json string of response """ jdata = Base_login.set_params(self, jsonf, **kw) headers = Base_login.set_header(self, jessionid, token=token) print(jdata) url = jdata["url"] data = jdata["body"] print('The request method is:', jdata["method"]) if jdata["method"] == 'POST': resp = requests.post(url, data=data, headers=headers) else: resp = requests.get(url, params=data, headers=headers) assert resp.status_code == 200, 'requests is bad, request code is: %s' % resp.status_code print(resp.json()) return resp.json() def deal_result(self, resp, id): """ deal with resp and return need datalist :param resp: response of inquire result :param id: param for you need :param kwargs: :return: """ print(type(resp)) if type(resp) == 'str': print('111') redic = json.loads(resp.decode('utf-8')) else: redic = resp datalist = redic['data']['dataList'] idlist = [] for data in datalist: if id in data: idlist.append(data[id]) print('id list is:', idlist) if len(idlist) == 1: return idlist[0] else: return idlist def get_datavalue(self, resp, key): # print(type(resp)) if type(resp) == 'str': print('111') redic = json.loads(resp.decode('utf-8')) else: redic = resp datalist = redic['data']['dataList'] value = datalist[0][key] print(value) return value def delorupdate(self, jsonf, updateid, jessionid, model='update', token='', **kwargs): """ if request is del or update ,updata spacial json file. :param jsonf: update json file :param updateid: modify id :param model: update or del :param kwargs: update keyword :return: """ headers = Base_login.set_header(self, jessionid, token=token) with open(jsonf, 'r') as jp: datad = json.loads(jp.read()) print('data is:', datad) updateid = str(updateid) datad['url'] = datad['url'].replace('modifyid', updateid) print('url is:', datad['url']) if model == 'update': datad['body'] = {} for updated in kwargs: datad['body'][updated] = kwargs[updated] resp = requests.post(datad['url'], data=datad['body'], headers=headers) else: resp = requests.post(datad['url'], headers=headers) print('new data is:', datad) assert resp.status_code == 200, 'request faild!' print(resp.json()) return resp.json() if __name__ == '__main__': bl = Base_login() fp = '../Test_data/json/system/inquireuser.json' fd = '../Test_data/json/system/deleteuser.json' jess, token = bl.check_login(r'http:xxxxxxx/login', 'admin', '123456') resp = bl.reqUrl(fp, jess, token, mvnoCode='autotest1') dl, idl = bl.deal_result(resp, 'userId') rr = bl.delorupdate(fd, idl[0], jess, 'delete', token)

좋은 웹페이지 즐겨찾기