Q:什么是断言?
A:我理解的断言就是一个命题,在程序执行中,命题为真则通过,命题为假则不通过。
关于assert用法,参考菜鸟教程:https://www.runoob.com/python3/python3-assert.html
总结以下9种python断言方式
1.状态
def test_get(self):
r = requests.get('https://httpbin.testing-studio.com/get')
print(r.next)
print(r.json())
print(r.status_code)
assert r.status_code == 200
2.json
def test_post_json(self):
payload = {
"level": 1,
"name": "zizi"
}
r = requests.post('https://httpbin.testing-studio.com/post', json=payload)
print(r.text)
assert r.json()['json']['level'] == 1
3.list结构里的json
def test_hogwarts_json(self):
r = requests.get('https://home.testing-studio.com/categories.json')
print(r.text)
assert r.status_code == 200
print(jsonpath.jsonpath(r.json(), '$..name')) #打印出所有的name
assert r.json()['category_list']['categories'][0]['name'] == "开源项目" #json断言
4.jsonpath
def test_hogwarts_json(self):
r = requests.get('https://home.testing-studio.com/categories.json')
print(r.text)
assert r.status_code == 200
print(jsonpath.jsonpath(r.json(), '$..name')) #打印出所有的name
assert jsonpath.jsonpath(r.json(),'$..name')[0] == "开源项目" #jsonpath断言
5.assert_that
def test_hamcrest(self):
r = requests.get('https://home.testing-studio.com/categories.json')
assert_that(r.json()['category_list']['categories'][0]['name'], equal_to("开源项目")) #assert_that
6.post_xml
def test_post_xml(self):
xml = """<xml version='1.0' encoding='utf-8'><a>6</a>"""
headers = {"Content-Type": "application/xml"}
r = requests.post('https://httpbin.testing-studio.com/post', data=xml,headers=headers).text
print(r.text)
7.files
def test_files(self):
url = 'https://httpbin.testing-studio.com/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print(r.text)
8.header
def test_header(self):
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get('https://httpbin.testing-studio.com/get', headers=headers)
print(r.text)
assert r.json()['headers']["User-Agent"] == "my-app/0.0.1"
9.cookie
def test_cookie(self):
cookies = dict(cookies_are='working')
r = requests.get('https://httpbin.testing-studio.com/get', cookies=cookies)
print(r.text)
assert r.json()['headers']["Cookie"] == "cookies_are=working"
网友评论