requests-fixture/excel传参使用

import pytest
import requests

@pytest.fixture
def get_weather():
url = “https://jisutqybmf.market.alicloudapi.com/weather/query”

query = {
    "city": "上海"
}
header = {
    "Authorization": "APPCODE 36a6d64593884af1971d218d14a23f9d"
}
r = requests.get(url=url, params=query, headers=header)
return r.json()

def test_create_topic(get_weather):
result = get_weather[‘result’]

city = result['city']
date = result['date']
week = result['week']
weather = result['weather']
content = f'今天是{date},{week},这里是{city},今天天气{weather}。\n'
index_values = result['index']
for val in index_values:
    content += f'{val["iname"]}-{val["ivalue"]}-{val["detail"]}\n'

print(content)

url = 'http://49.233.108.117:3000/api/v1/topics'
json_data = {
    "accesstoken": "ce47cf2a-e98e-42b8-b2c8-794566a9b10d",
    "title": f"{city}-{date}-{weather}",
    "tab": "ask",
    'content': content
}
r = requests.post(url=url, json=json_data)
assert r.status_code == 200

def test_wechat(get_weather):
result = get_weather[‘result’]

city = result['city']
date = result['date']
week = result['week']
weather = result['weather']
content = f'今天是{date},{week},这里是{city},今天天气{weather}。\n'
index_values = result['index']
for val in index_values:
    content += f'{val["iname"]}-{val["ivalue"]}-{val["detail"]}\n'

url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9d1dd035-d81c-4961-99ea-b27f33e048d8"
jsondata= {
"msgtype": "text",
"text": {
    "content": content
}

}

r = requests.post(url,json=jsondata)
assert r.status_code == 200

主要使用 @pytest.fixture 进行参数传递
主要使用方式,函数有返回值。在下一个接口中通过函数的名称进行参数传递。

Excel做数据驱动
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
import os
import json
import pytest
import requests

excel_file = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(file))),‘testdata’,‘post_data.xlsx’)

加载文件

wb = load_workbook(excel_file)

处理worksheet

print(wb.sheetnames)

访问post_data 单元表

ws:Worksheet = wb[‘post_data’]
testdata = []
vals = ws.values

去掉Excel中第一行数据

next(vals)
for row in vals:
testdata.append(row)

@pytest.mark.parametrize(‘id,json_data,excpet_status_code,excpet_msg,result’,testdata)
def test_create_topic(id,json_data,excpet_status_code,excpet_msg,result):

url = 'http://49.233.108.117:3000/api/v1/topics'
json_data = json.loads(json_data)
r = requests.post(url,json=json_data)
print(r.status_code ,r.json())
assert r.status_code == excpet_status_code
assert r.json() == json.loads(excpet_msg)

测试数据一般都放在test_data中

Guess you like

Origin blog.csdn.net/HAHH404/article/details/121608276