接口 - 基本请求与响应断言
一、基本常用请求
- get query
- post body
- form请求(详情参考:https://www.cnblogs.com/bester-ace/articles/9234229.html)
- 结构化请求:json、xml、json rpc
- binary
#!/usr/bin/python3.8.9
# -*- coding: utf-8 -*-
# @Author : Tina Yu
# @Time : 2022-2-20 15:38
import requests
from jsonpath import jsonpath
class TestDemo:
def test_get(self):
r = requests.get('https://httpbin.testing-studio.com/get')
print(r.status_code)
print(r.json())
print(r.text)
assert r.status_code == 200
def test_query(self):
"""
query使用params,请求参数在url后面。
"""
payload = {
'level': 1,
'name': "tina"
}
r = requests.get('https://httpbin.testing-studio.com/get', params=payload)
print(r.text)
assert r.status_code == 200
def test_post_form(self):
"""
form格式,使用data;请求的参数在请求体中。
"""
payload = {
"user_name": "tina",
"pwd": 123456
}
r = requests.post('https://httpbin.testing-studio.com/post', data=payload)
print(r.text)
# assert r.status_code == 200
assert r.json()['form']['pwd'] == '123456'
def test_post_json(self):
"""
json格式,使用json;请求的参数在请求体中。
"""
payload = {
"user_name": "tina",
"pwd": 123456
}
r = requests.post('https://httpbin.testing-studio.com/post', json=payload)
print(r.text)
# assert r.status_code == 200
assert r.json()['json']['pwd'] == 123456
def test_header(self):
"""
r.json()['headers']['xxx']获取header中某个字段值,然后做校验
"""
r = requests.get("https://httpbin.testing-studio.com/get", headers={"h": "tina"})
print(r.json())
print(r.headers)
assert r.json()['headers']['H'] == "tina"
二、响应断言
- json断言
- json path
def test_assert_by_json(self):
"""
jsonpath需要安装:pip install jsonpath,导入:from jsonpath import jsonpath
"""
r = requests.get("https://home.testing-studio.com/categories.json")
print(r.text)
assert r.status_code == 200
# 通过json直接获取结果做校验
assert r.json()['category_list']['categories'][0]['name'] == '开源项目'
# 通过jsonpath获取结果做校验
assert jsonpath(r.json(), '$..name')[0] == '开源项目'
- xml 断言 、xpath 断言
def test_assert_by_xml(self):
"""
安装:pip install requests_xml
导入:from requests_xml import XMLSession
"""
session = XMLSession()
r = session.get('https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss')
print(r.xml.text)
link_list = r.xml.links # 获取链接地址的列表
item = r.xml.xpath('//item', first=True) # 获取第一个节点的值
print(item.text)
assert link_list[0] == 'http://www.nasa.gov/image-feature/eclipse-over-antarctica'
- xml 解析
- hamcrest 断言体系(官网:hamcrest.org)
def test_assert_by_hamcrest(self):
"""
安装:pip install hamcrest
导入:from hamcrest import *
"""
a = 1
b = 3
c = a + b
assert_that(c, equal_to(4))
本文来自博客园,作者:于慧妃,转载请注明原文链接:https://www.cnblogs.com/fengyudeleishui/p/15943869.html