httprunner 环境变量、Debugtalk辅助函数、setup/teardown_hooks使用、参数化

环境变量设置

1.项目中添加.env的文件

2.在项目中使用${.env(变量名)}进行使用

- config:
    name: "phpwind论坛的首页模拟"
    base_url: ${ENV(URL)}
    requests:
      headers:
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
        "Accept-Encoding": "gzip, deflate"
        "Accept-Language": "zh-CN,zh;q=0.9"
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
    export:
      - code
      - info
      - contenttype
      - content

- test:
    name: "phpwind论坛的首页模拟"
    request:
      url: "/phpwind/"
      method: GET
    extract:
      - code: status_code
      - info: reason
      - contenttype: headers.Content-Type
      - content: 'title="(.+?)">biaoti826</a>'
    validate:
      - eq: ["status_code",200]
      - str_eq: [$content,'biaoti826']
View Code

Debugtalk辅助函数

1.在debugtalk.py中编写的方法可以在httprunner中的yml文件中使用(${方法名})

import requests

def get_token_id():
    get_param_data ={'grant_type': 'client_credential',
                     'appid': 'wxec83eaada223a9c8',
                     'secret': '1867d7f1cabb3bafae0b7304e8251a09'}
    response = requests.get(url='https://api.weixin.qq.com/cgi-bin/token',
                            params=get_param_data)
    return response.json()['access_token']


if __name__ == '__main__':
    print(get_token_id())
View Code
# debugtalk使用
- config:
    name: "获取token -- 用户管理~查看粉丝基本信息操作"
    base_url: "https://api.weixin.qq.com"
    variables:
      - tokenid: ${get_token_id()}

- test:
    name: "查看粉丝基本信息"
    request:
      url: "/cgi-bin/user/info"
      method: GET
      params:
        access_token: $tokenid
        openid: "od-53v0GMqGTEiPY-QC549RTXkCk"
        lang: zh_CN
    validate:
      - eq: [content.language,zh_CN]
View Code

 setup/teardown_hooks使用

1.既可以写在config中,也可以写在test中

- config:
    name: "获取token -- 用户管理~查看粉丝基本信息操作"
    base_url: "https://api.weixin.qq.com"
    variables:
      - tokenid: ${get_token_id()}
    setup_hooks:
      - ${setup_case()}
    teardown_hooks:
      - ${teardown_case()}

- test:
    name: "查看粉丝基本信息"
    request:
      url: "/cgi-bin/user/info"
      method: GET
      params:
        access_token: $tokenid
        openid: "od-53v0GMqGTEiPY-QC549RTXkCk"
        lang: zh_CN
    setup_hooks:
      - ${setup_step()}
    teardown_hooks:
      - ${teardown_step()}
    validate:
      - eq: [content.language,zh_CN]
View Code

参数化使用

方法一:使用test_suites套件

1.新建test_suites文件夹

2.新建yaml文件如下

config:
  name: "test suite"

testcases:
  - name: "Create tags"
    testcase: testcases\httprunnerhomework02\create_tag.yml
    parameters:
      tag_name: ['test11','test12','test13','test14','test15','test16','test17','test18','test19','test20']
View Code

3.修改被调用的测试用例使用$变量名进行引用

- config:
    name: "创建标签"
    base_url: ${ENV(URL)}
    variables:
      - tokenid: ${get_token_id()}

- test:
    name: "创建标签"
    request:
      url: "/cgi-bin/tags/create"
      method: POST
      headers:
        Content_Type: "application/json"
      params:
        access_token: $tokenid
      json: {   "tag" : {     "name" : $tag_name   } }
    validate:
      - eq: ['status_code',200]
View Code

4.使用 hrun test_suites\yml文件执行

方法二:基于方法一,使用csv文件进行参数化

1.新建data文件夹存放.csv文件;文件内容如下

searchword,result
12306,12306_百度搜索
newdream,newdream_百度搜索
天天向上,天天向上_百度搜索
View Code

2.P(文件路径)  :httprunner内置的解析 csv文件的函数

config:
  name: "test suite"

testcases:
  - name: "Create tags"
    testcase: testcases\httprunnerday3\baidu_search_test.yml
    parameters:
      searchword-result: ${P(data/info.csv)}
View Code

3.修改被调用的测试用例使用$变量名进行引用

# 模拟请求头
- config:
    name: "验证百度搜索是否正确"
    base_url: "https://www.baidu.com"
    export:
      - title

- test:
    name: "百度搜索请求"
    request:
      url: "/s"
      method: GET
      params:
        wd: $searchword
      headers:
        User-Agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
        Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
        Accept-Encoding: "gzip, deflate, br"
        Accept-Language: "zh-CN,zh;q=0.9"
    extract:
      - title: <title>(.+?)</title>
    validate:
      - eq: ["status_code",200]
      - str_eq: [$title, $result]
View Code

4.使用 hrun test_suites\yml文件执行

备注:1参数名称必须与csv文件表头一致,2.如需要传更多参数,需要用 - ,如上的:searchword-result

方法三:基于方法一,使用debugtalk.py文件进行参数化

1.在debugtalk.py中编写随机整数参数化

def get_randomints(min, max, count=3):
    randomints_list = []
    for i in range(count):
        randomints_list.append(random.randint(min, max))
    return randomints_list
View Code

2.在测试套件yml文件中${函数方法()}引用方法,备注,这里只接受list数据

config:
  name: "test suite"

testcases:
  - name: "Create tags"
    testcase: testcases\httprunnerday3\baidu_search_debugfalkdata_test.yml
    parameters:
      searchword: ${get_randomints(1,100,10)}
View Code

3.调用的测试用例中$变量名进行引用

# 模拟请求头
- config:
    name: "验证百度搜索是否正确"
    base_url: "https://www.baidu.com"
    export:
      - title

- test:
    name: "百度搜索请求"
    request:
      url: "/s"
      method: GET
      params:
        wd: $searchword
      headers:
        User-Agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
        Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
        Accept-Encoding: "gzip, deflate, br"
        Accept-Language: "zh-CN,zh;q=0.9"
    extract:
      - title: <title>(.+?)</title>
    validate:
      - eq: ["status_code",200]
View Code

4.使用 hrun test_suites\yml文件执行测试套件

相应方法:

随机整形参数化

def get_randomints(min, max, count=3):
    randomints_list = []
    for i in range(count):
        randomints_list.append(random.randint(min, max))
    return randomints_list
View Code

顺序整形参数化

def get_seq_ints(min, max, step=1, count=None):
    seqint_list = list(range(min, max, step))
    if count:
        return seqint_list[0: count]
    else:
        return seqint_list
View Code

随机长度的字符串

def get_str(randomlength, count=3):
    str_list = []
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(count):
        ran_str = ''
        for i in range(randomlength):
            ran_str += base_str[random.randint(0, length)]
        str_list.append(ran_str)
    return str_list
View Code

随机生成手机号

def get_random_mobilephone(count=1):
    phone_list = []
    for i in range(count):
        # 第二位数字
        second = [3, 4, 5, 7, 8][random.randint(0, 4)]
        # 第三位数字
        third = {
            3: random.randint(0, 9),
            4: [5, 7, 9][random.randint(0, 2)],
            5: [i for i in range(10) if i != 4][random.randint(0, 8)],
            7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
            8: random.randint(0, 9),
        }[second]

        # 最后八位数字
        suffix = random.randint(9999999,100000000)
        phone_list.append("1{}{}{}".format(second, third, suffix))
    return phone_list
View Code

 

posted @ 2020-06-16 19:07  Alin。  阅读(687)  评论(0编辑  收藏  举报