Пример #1
0
def post(url,
         params=None,
         data=None,
         files=None,
         json=None,
         headers=None,
         cookies=None):
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url,
                                 data=data,
                                 files=files,
                                 params=params,
                                 headers=headers,
                                 json=json,
                                 cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间,单位为毫秒
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Пример #2
0
def test_post_json(pub_data):  # 上报案件
    method = "POST"  # 请求方法,全部大写
    feature = "案件管理"  # allure报告中一级分类
    story = '案件发现'  # allure报告中二级分类
    title = "待受理-上报案件"  # allure报告中用例名字
    uri = f'/api/web/events/report-message?id=false&token={pub_data["token"]}'  # 接口地址
    # post请求json数据,注意数据格式为字典或者为json串 为空写None
    data = {
        'reportContent':
        '{"city":"上海","district":20,"eventName":"阻塞消防通道的违规行为","eventDescription":"玩のfrv","street":"0","source":"1","degree":"1","community":null,"address":"王二狗","addressNote":"无二等分v吧","grid_center":"2020155","audios":[],"videos":[],"scenes":[],"result":[],"areaType":"1","eventType":{"level_1":"事件","level_2":"设施管理","level_3":"违规占用地下公共人行通道"},"lngCd":0,"latCd":0}',
        'handleChannel': '3',
        'type': '1'
    }

    status_code = 200  # 响应状态码
    expect = "200"  # 预期结果
    # --------------------分界线,下边的不要修改-----------------------------------------
    # method,pub_data和url为必传字段
    r = request_tool.request(method=method,
                             url=uri,
                             pub_data=pub_data,
                             data=data,
                             status_code=status_code,
                             expect=expect,
                             feature=feature,
                             story=story,
                             title=title)
    log_tool.info('----------------------上报成功---------------------')
    assert r.json()["code"] == 200 and r.json()["data"] == True  # 断言
Пример #3
0
def test_get_params(pub_data):  # 查询待受理案件列表
    method = "GET"  # 请求方法,全部大写
    feature = "案件管理"  # allure报告中一级分类
    story = '案件发现'  # allure报告中二级分类
    title = "待受理-查询案件"  # allure报告中用例名字
    uri = f"/api/web/events/report-list?start={open()}&end={open1()}&pageSize=10&page=1&sort=event_time&sort_type=0&isResolve=0&token={pub_data['token']}"  # 接口地址
    # post请求json数据,注意数据格式为字典或者为json串 为空写None
    # params = {"phone":'18103909786'}
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json;charset=UTF-8'
    }
    status_code = 200  # 响应状态码
    expect = "200"  # 预期结果
    # --------------------分界线,下边的不要修改-----------------------------------------
    # method,pub_data和url为必传字段
    r = request_tool.request(method=method,
                             url=uri,
                             pub_data=pub_data,
                             status_code=status_code,
                             expect=expect,
                             feature=feature,
                             story=story,
                             title=title,
                             headers=headers)
    j = r.json()
    p = j['data']['items'][0]['eventId']
    #print(p)
    d["eventId"] = p
    assert r.json()["code"] == 200 and r.json()["data"] != None
    log_tool.info('----------------------查询成功----------------------')
Пример #4
0
def put_request(*args, **kwargs):
    '''
    Put请求
    :param url:
    :param data:
    :param header:
    :return:
    '''

    try:

        response = requests.put(*args, **kwargs)
    except requests.RequestException as e:
        log_tool.error('%s%s' % ('RequestException url: ', kwargs['url']))
        log_tool.error(e)
        return ()

    except Exception as e:
        print('%s%s' % ('Exception url: ', kwargs['url']))
        print(e)
        return ()

    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response
Пример #5
0
 def start_browser(self, browser='chrome'):
     '''
     启动浏览器
     :param browser: 浏览器类型
     '''
     if self.driver:
         log_tool.info("浏览器以启动,请勿再次启动浏览器。")
         return self
     try:
         if browser == "firefox" or browser == "ff":
             self.driver = webdriver.Firefox()
         elif browser == "chrome":
             chrome_options = Options()
             chrome_options.binary_location = BROWSER_PATH
             # chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
             self.driver = webdriver.Chrome(executable_path=DRIVER_PATH,
                                            options=chrome_options)
             self.driver.maximize_window()
             self.wait_time()
         elif browser == "internet explorer" or browser == "ie":
             self.driver = webdriver.Ie()
         elif browser == "opera":
             self.driver = webdriver.Opera()
         elif browser == "chrome_headless":
             chrome_options = Options()
             chrome_options.add_argument('--headless')
             chrome_options.add_argument('--disable-gpu')
             chrome_options.add_argument('--no-sandbox')
             chrome_options.add_argument('--disable-dev-shm-usage')
             chrome_options.add_argument("--window-size=1920,1080")
             chrome_options.binary_location = BROWSER_PATH
             # chrome_options.add_experimental_option('excludeSwitches',['enable-automation'])
             self.driver = webdriver.Chrome(executable_path=DRIVER_PATH,
                                            options=chrome_options)
             self.wait_time()
         elif browser == "chrome_debugger":
             print("chrome_debugger模式")
             chrome_options = Options()
             chrome_options.add_experimental_option("debuggerAddress",
                                                    "127.0.0.1:9111")
             chrome_options.binary_location = BROWSER_PATH
             # chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
             self.driver = webdriver.Chrome(executable_path=DRIVER_PATH,
                                            options=chrome_options)
             self.driver.maximize_window()
             self.wait_time()
         elif browser == 'edge':
             self.driver = webdriver.Edge()
         else:
             log_tool.error(
                 "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
                 % browser)
             raise NameError(
                 "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
                 % browser)
     except WebDriverException:
         log_tool.error("启动浏览器失败,请检查webdriver是否配置,或者webdriver版本是否和浏览器匹配")
         raise
     self.shot("-------测试开始,启动{}浏览器成功-------".format(browser))
Пример #6
0
 def shot(self, *args, **kwargs):
     message = ""
     for i in range(len(args)):
         message += "{} "
     log_tool.info(message.format(*args))
     #todo
     allure.attach(self.screenshot_as_png(),
                   message.format(*args) + "操作成功",
                   allure.attachment_type.PNG)
Пример #7
0
 def _func(*args, **kwargs):
     r = func(*args, **kwargs)
     request = "-------------------request-------------" \
               "\n{0}\n{1}\n{2}".format(r.url, string_tool.dic_to_str(r.request.headers), r.request.body)
     log_tool.info(request)
     response = "---------------response----------------" \
                "\n{0}\n{1}\n{2}".format(r.status_code, string_tool.dic_to_str(r.headers), r.text)
     log_tool.info(response)
     allure.attach(request, 'request', allure.attachment_type.TEXT)
     allure.attach(response, 'response', allure.attachment_type.TEXT)
     return r
Пример #8
0
def test_get_register(pub_data):  #立案
    method = "PUT"  #请求方法,全部大写
    feature = "案件管理"  # allure报告中一级分类
    story = '案件立案'  # allure报告中二级分类
    title = "待立案-立案操作"  # allure报告中用例名字
    uri = f"/api/web/events/{b['eventId']}?token={pub_data['token']}&id={b['eventId']}"  # 接口地址
    # post请求json数据,注意数据格式为字典或者为json串 为空写None
    #params = {"phone":'18103909786'}
    headers = {"Content-Type": "application/json;charset=utf-8"}
    data = {
        "data": {
            "eventName": "阻塞消防通道的违规行为",
            "address": "王二狗",
            "addressNote": "无二等分v吧",
            "eventDescription": "玩のfrv",
            "eventType": {
                "level_1": "事件",
                "level_2": "设施管理",
                "level_3": "违规占用地下公共人行通道"
            },
            "community": "",
            "source": 1,
            "images": [],
            "status": 13,
            "confirm_info": {
                "description": "案件情况属实,予以立案,请派遣处置!"
            }
        }
    }

    status_code = 200  # 响应状态码
    expect = "2000"  # 预期结果
    # --------------------分界线,下边的不要修改-----------------------------------------
    # method,pub_data和url为必传字段
    r = request_tool.request(method=method,
                             url=uri,
                             pub_data=pub_data,
                             status_code=status_code,
                             json_data=data,
                             expect=expect,
                             feature=feature,
                             story=story,
                             title=title,
                             headers=headers)
    p = r.json()
    p1 = p['data']["eventId"]
    l["eventId"] = p1
    print(p1)

    assert r.json()["code"] == 200 and r.json()["data"] != None

    log_tool.info('----------------------立案成功----------------------')
Пример #9
0
def get(url, params=None, headers=None, cookies=None):
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.get(url=url, params=params, headers=headers, cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Пример #10
0
 def start_browser(self, browser='chrome'):
     '''
     启动浏览器
     :param browser: 浏览器类型
     '''
     if BaseUI.driver:
         log_tool.info("浏览器以启动,请勿再次启动浏览器。")
         return
     try:
         if browser == "firefox" or browser == "ff":
             BaseUI.driver = webdriver.Firefox()
         elif browser == "chrome":
             driver_path = DRIVER_PATH
             BaseUI.driver = webdriver.Chrome(driver_path)
             BaseUI.driver.maximize_window()
             BaseUI.driver.implicitly_wait(10)
         elif browser == "internet explorer" or browser == "ie":
             BaseUI.driver = webdriver.Ie()
         elif browser == "opera":
             BaseUI.driver = webdriver.Opera()
         elif browser == "chrome_headless":
             chrome_options = Options()
             chrome_options.add_argument('--headless')
             BaseUI.driver = webdriver.Chrome(DRIVER_PATH,
                                              options=chrome_options)
         elif browser == "chrome_debugger":
             print("chrome_debugger模式")
             chrome_options = Options()
             chrome_options.add_experimental_option("debuggerAddress",
                                                    "127.0.0.1:9222")
             # chrome_options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
             BaseUI.driver = webdriver.Chrome(DRIVER_PATH,
                                              options=chrome_options)
             BaseUI.driver.maximize_window()
             BaseUI.driver.implicitly_wait(10)
         elif browser == 'edge':
             BaseUI.driver = webdriver.Edge()
         else:
             log_tool.error(
                 "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
                 % browser)
             raise NameError(
                 "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"
                 % browser)
     except WebDriverException:
         log_tool.error("启动浏览器失败,请检查webdriver是否配置,或者webdriver版本是否和浏览器匹配")
         raise
     self.shot("-------测试开始,启动{}浏览器成功-------".format(browser))
Пример #11
0
def post_json(url, json=None, headers=None, cookies=None):
    if headers == None:
        headers={}
    headers['content-type']='application/json;;charset=UTF-8'
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        print(url)
    try:
        response = requests.post(url, headers=headers, json=json,cookies=cookies)
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', url))
        log_tool.error(e)
        return ()
    # time_consuming为响应时间,单位为毫秒
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Пример #12
0
def post_request_multipart(*args, **kwargs):
    '''
    提交Multipart/form-data 格式的Post请求
    :param url:
    :param data:
    :param header:
    :param file_parm:
    :param file:
    :param type:
    :return:
    '''

    response = requests.post(*args, **kwargs)
    # time_consuming为响应时间,单位为毫秒
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response
Пример #13
0
def test_post_json(pub_data):

    method = "POST"  #请求方法,全部大写
    feature = "用户模块"  # allure报告中一级分类
    story = '用户登录'  # allure报告中二级分类
    title = "全字段正常流_1"  # allure报告中用例名字
    uri = "/api/app/users/login"  # 接口地址
    headers = {'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=UTF-8'}
    # post请求json数据,注意数据格式为字典或者为json串 为空写None
    json_data = {"username": "******", "password": "******"}
    status_code = 200  # 响应状态码
    expect = "200"  # 预期结果
    # --------------------分界线,下边的不要修改-----------------------------------------
    # method,pub_data和url为必传字段
    r=request_tool.request(method=method,url=uri,headers=headers,pub_data=pub_data,json_data=json_data,status_code=status_code,expect=expect,feature=feature,story=story,title=title)
    log_tool.info('----------------------登录成功----------------------')

    return r.json()["data"]["token"]
Пример #14
0
def put(url, data, header=None, cookies=None):
    if not (url.startswith('http://') or url.startswith('https://')):
        url = '%s%s' % ('http://', url)
        log_tool.debug(url)

    try:
        if data is None:
            response = requests.put(url=url, headers=header, cookies=cookies)
        else:
            response = requests.put(url=url, params=data, headers=header, cookies=cookies)

    except Exception as e:
        log_tool.error('%s%s' % ('RequestException url: ', url))
        log_tool.error(e)
        return ()
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)

    return response
Пример #15
0
def request(args: object, kwargs: object) -> object:
    '''
    Get请求
    :param url:
    :param data:
    :param header:
    :return:
    '''
    try:
        response = requests.request(*args, **kwargs)
    except requests.RequestException as e:
        log_tool.error('%s%s' % ('Exception url: ', kwargs['url']))
        log_tool.error(e)
        return ()
    except Exception as e:
        log_tool.error('%s%s' % ('Exception url: ', kwargs['url']))
        return ()
    time_consuming = response.elapsed.microseconds / 1000
    log_tool.info('----请求用时: %s 秒数' % time_consuming)
    return response
Пример #16
0
def test_accept_and_hear_a_case(pub_data):  # 案件受理
    method = "PATCH"  # 请求方法,全部大写           #
    feature = "案件管理"  # allure报告中一级分类
    story = '案件发现'  # allure报告中二级分类
    title = "待受理-受理"  # allure报告中用例名字
    url = f"/api/web/events/{d['eventId']}?token={pub_data['token']}&id={d['eventId']}"  # 接口地址
    log_tool.info('受理')
    # params = {"phone":'18103909786'}
    headers = {"Content-Type": "application/json;charset=utf-8"}

    data = {
        "data": {
            "status": "12",
            "desc": "同意受理!",
            "withNext": 0,
            "nextDesc": ""
        }
    }

    status_code = 200  # 响应状态码
    expect = "200"  # 预期结果
    # --------------------分界线,下边的不要修改-----------------------------------------
    # method,pub_data和url为必传字段
    r = request_tool.request(method=method,
                             url=url,
                             pub_data=pub_data,
                             status_code=status_code,
                             headers=headers,
                             expect=expect,
                             feature=feature,
                             story=story,
                             title=title,
                             json_data=data)
    p = r.json()
    t = p['data']['eventId']
    b["eventId"] = t
    #print(t)
    assert r.json()["code"] == 200 and r.json()["data"] != None

    log_tool.info('----------------------受理成功----------------------')
Пример #17
0
def test_d3_addTeacher(pub_data):

    with allure.step('第1步:准备请求报文'):
        log_tool.info(
            '\n-----------------test_case/test_login/test_test_login.py::d3_addTeacher-----------------'
        )
        url = config.api_url + '/crmapi/admin/addTeacher'
        allure.attach(url, '请求地址', allure.attachment_type.TEXT)
        log_tool.info('\n请求地址:\n' + url)

        headers = {
            "addr": "上海市虹口区",
            "UserID": "0",
            "ip": "124.77.86.126",
            "Token": "5954bc3637eb4ce8aefa71afbd9d3d72",
            "Content-Type": "application/json;charset=UTF-8"
        }
        allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求头:\n' +
                      json.dumps(headers, ensure_ascii=False, indent=4))

        headers['addr'] = '上海市虹口区'.encode('utf-8').decode('latin-1')

        req = {
            "name": f.name(),
            "username": f.user_name(),
            "paaword": "7a64d3bd06bc8e17d2100f846e719fd6",
            "rule": ["teacher"]
        }
        allure.attach(json.dumps(req, ensure_ascii=False, indent=4), '请求正文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求正文:\n' +
                      json.dumps(req, ensure_ascii=False, indent=4))

    with allure.step('第2步:调用接口'):
        resp = requests.post(url, headers=headers, json=req)

    with allure.step('第3步:接收响应'):
        data = resp.json()
        allure.attach(json.dumps(data, ensure_ascii=False, indent=4), '响应报文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n响应报文:\n' +
                      json.dumps(data, ensure_ascii=False, indent=4))

    with allure.step('第4步:判断结果'):
        allure.attach("resp.status_code == 200", '断言条件',
                      allure.attachment_type.TEXT)
        log_tool.info('\n断言条件:\n' + 'resp.status_code == 200')
        assert data['code'] == 20000

    with allure.step('第5步:提取数据'):
        # pub_data['data_name']='data_value';
        allure.attach('无', '提取数据列表', allure.attachment_type.TEXT)
        log_tool.info('\n提取数据列表:\n' + '无')
        log_tool.info('\n\n\n')
Пример #18
0
def test_d5_queryStuList(pub_data):

    with allure.step('第1步:准备请求报文'):
        log_tool.info(
            '\n-----------------test_case/test_login/test_test_login.py::d5_queryStuList-----------------'
        )
        url = config.api_url + '/crmapi/admin/stu/queryStuList?pageNum=1&pageSize=10'
        allure.attach(url, '请求地址', allure.attachment_type.TEXT)
        log_tool.info('\n请求地址:\n' + url)

        headers = {
            "addr": "上海市虹口区",
            "UserID": "0",
            "ip": "124.77.86.126",
            "Token": "5954bc3637eb4ce8aefa71afbd9d3d72",
            "Content-Type": "application/json;charset=UTF-8"
        }
        allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求头:\n' +
                      json.dumps(headers, ensure_ascii=False, indent=4))

        headers['addr'] = '上海市虹口区'.encode('utf-8').decode('latin-1')

        req = {
            "className": "",
            "classId": 0,
            "stuId": 0,
            "stuName": "",
            "age1": 0,
            "age2": 0,
            "cert": "",
            "province": "",
            "city": "",
            "education": "",
            "feeUnpayed": 0,
            "feePayed": 0,
            "badDebt": 0,
            "discountsName": "",
            "phone": "",
            "discountsAmount": 0,
            "employmentType": "",
            "homeAddr": "",
            "comAddr": ""
        }
        allure.attach(json.dumps(req, ensure_ascii=False, indent=4), '请求正文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求正文:\n' +
                      json.dumps(req, ensure_ascii=False, indent=4))

    with allure.step('第2步:调用接口'):
        resp = requests.post(url, headers=headers, json=req)

    with allure.step('第3步:接收响应'):
        data = resp.json()
        allure.attach(json.dumps(data, ensure_ascii=False, indent=4), '响应报文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n响应报文:\n' +
                      json.dumps(data, ensure_ascii=False, indent=4))

    with allure.step('第4步:判断结果'):
        allure.attach("resp.status_code == 200", '断言条件',
                      allure.attachment_type.TEXT)
        log_tool.info('\n断言条件:\n' + 'resp.status_code == 200')
        assert data['code'] == 20000

    with allure.step('第5步:提取数据'):
        # pub_data['data_name']='data_value';
        allure.attach('无', '提取数据列表', allure.attachment_type.TEXT)
        log_tool.info('\n提取数据列表:\n' + '无')
        log_tool.info('\n\n\n')
Пример #19
0
def test_d2_info(pub_data):

    with allure.step('第1步:准备请求报文'):
        log_tool.info(
            '\n-----------------test_case/test_login/test_test_login.py::d2_info-----------------'
        )
        url = config.api_url + '/crmapi/user/info?token=5954bc3637eb4ce8aefa71afbd9d3d72'
        allure.attach(url, '请求地址', allure.attachment_type.TEXT)
        log_tool.info('\n请求地址:\n' + url)

        headers = {
            "addr": "上海市虹口区",
            "UserID": "0",
            "ip": "124.77.86.126",
            "Token": "5954bc3637eb4ce8aefa71afbd9d3d72"
        }
        allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求头:\n' +
                      json.dumps(headers, ensure_ascii=False, indent=4))

        headers['addr'] = '上海市虹口区'.encode('utf-8').decode('latin-1')

    with allure.step('第2步:调用接口'):
        resp = requests.get(url, headers=headers)

    with allure.step('第3步:接收响应'):
        data = resp.json()
        allure.attach(json.dumps(data, ensure_ascii=False, indent=4), '响应报文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n响应报文:\n' +
                      json.dumps(data, ensure_ascii=False, indent=4))

    with allure.step('第4步:判断结果'):
        allure.attach("resp.status_code == 200", '断言条件',
                      allure.attachment_type.TEXT)
        log_tool.info('\n断言条件:\n' + 'resp.status_code == 200')
        assert data['code'] == 20000

    with allure.step('第5步:提取数据'):
        # pub_data['data_name']='data_value';
        allure.attach('无', '提取数据列表', allure.attachment_type.TEXT)
        log_tool.info('\n提取数据列表:\n' + '无')
        log_tool.info('\n\n\n')
Пример #20
0
def over_time():
    date_time = str(datetime.datetime.now())[0:19]
    log_tool.info("本条测试用例结束时间:{}".format(date_time))
Пример #21
0
    def start_browser(self, browser='chrome'):
        '''
        启动浏览器
        :param browser: 浏览器类型
        '''
        if BaseUI.driver:
            log_tool.info("浏览器以启动,请勿再次启动浏览器。")
            return
        try:
            if browser == "firefox" or browser == "ff":
                BaseUI.driver = webdriver.Firefox()
            elif browser == "chrome":
                driver_path = DRIVER_PATH
                BaseUI.driver = webdriver.Chrome(driver_path)
                BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "internet explorer" or browser == "ie":
                BaseUI.driver = webdriver.Ie()
            elif browser == "opera":
                BaseUI.driver = webdriver.Opera()
            elif browser == "chrome_headless":
                chrome_options = Options()
                chrome_options.add_argument('--headless')
                BaseUI.driver = webdriver.Chrome(DRIVER_PATH,options=chrome_options)
            elif browser == "chrome_debugger":
                print("chrome_debugger模式")
                chrome_options = Options()
                chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9111")
                BaseUI.driver = webdriver.Chrome(DRIVER_PATH, options=chrome_options)
                # BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "mobile":
                print("mobile模式")
                # mobileEmulation = {'deviceName': 'Galaxy S5'}
                # chrome_options = webdriver.ChromeOptions()
                # chrome_options.add_experimental_option('mobileEmulation', mobileEmulation)
                # BaseUI.driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=chrome_options)
                WIDTH = 320
                HEIGHT = 640
                PIXEL_RATIO = 3.0
                UA = 'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3'
                mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO},"userAgent": UA}
                options = webdriver.ChromeOptions()
                options.add_experimental_option('mobileEmulation', mobileEmulation)
                BaseUI.driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=options)
                BaseUI.driver.maximize_window()
                BaseUI.driver.implicitly_wait(10)
            elif browser == "headless":
                chrome_options = Options()
                # chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
                # chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
                # chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
                # chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
                # chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
                chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
                chrome_options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"  # 手动指定本机电脑使用的浏览器位置

                # 创建一个driver,进行后面的请求页面等操作,executable_path指定本机中chromedriver.exe的位置
                BaseUI.driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=DRIVER_PATH)

            elif browser == 'edge':
                BaseUI.driver = webdriver.Edge()
            else:
                log_tool.error("启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"% browser)
                raise NameError(
                    "启动浏览器失败,没有找到%s浏览器,请输入'ie', 'ff', 'opera', 'edge', 'chrome' or 'chrome_headless'"% browser)
        except WebDriverException:
            log_tool.error("启动浏览器失败,请检查webdriver是否配置,或者webdriver版本是否和浏览器匹配")
            raise
        self.shot("-------测试开始,启动{}浏览器成功-------".format(browser))
Пример #22
0
 def shot(self, *args, **kwargs):
     log_tool.info(" ".join(args))
     allure.attach(self.driver.get_screenshot_as_png(), " ".join(args),
                   allure.attachment_type.PNG)
Пример #23
0
 def shot(self, *args, **kwargs):
     message = ""
     for i in range(len(args)):
         message += "{} "
     log_tool.info(message.format(*args))
Пример #24
0
def test_d1_admin(pub_data):

    with allure.step('第1步:准备请求报文'):
        log_tool.info(
            '\n-----------------test_case/test_login/test_test_login.py::d1_admin-----------------'
        )
        url = config.api_url + '/crmapi/user/login/admin'
        allure.attach(url, '请求地址', allure.attachment_type.TEXT)
        log_tool.info('\n请求地址:\n' + url)

        headers = {
            "addr": "上海市虹口区",
            "ip": "124.77.86.126",
            "Content-Type": "application/json;charset=UTF-8"
        }
        allure.attach(json.dumps(headers, ensure_ascii=False, indent=4), '请求头',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求头:\n' +
                      json.dumps(headers, ensure_ascii=False, indent=4))

        headers['addr'] = '上海市虹口区'.encode('utf-8').decode('latin-1')

        req = {
            "username": "******",
            "password": md5('123456&key=guoyasoft'.encode('utf8')).hexdigest()
        }
        allure.attach(json.dumps(req, ensure_ascii=False, indent=4), '请求正文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n请求正文:\n' +
                      json.dumps(req, ensure_ascii=False, indent=4))

    with allure.step('第2步:调用接口'):
        resp = requests.post(url, headers=headers, json=req)

    with allure.step('第3步:接收响应'):
        data = resp.json()
        allure.attach(json.dumps(data, ensure_ascii=False, indent=4), '响应报文',
                      allure.attachment_type.TEXT)
        log_tool.info('\n响应报文:\n' +
                      json.dumps(data, ensure_ascii=False, indent=4))

    with allure.step('第4步:判断结果'):
        allure.attach("resp.status_code == 200", '断言条件',
                      allure.attachment_type.TEXT)
        log_tool.info('\n断言条件:\n' + 'resp.status_code == 200')
        assert data['code'] == 20000

    with allure.step('第5步:提取数据'):
        token = data['data']['token']
        pub_data['token'] = token
        # pub_data['data_name']='data_value';
        allure.attach('token=' + token, '提取数据列表', allure.attachment_type.TEXT)
        log_tool.info('\n提取数据列表:\n' + 'token=' + token)
        log_tool.info('\n\n\n')