最近学习Python,在代码测试阶段用学到断言功能,断言方法用于检查你认为应该满足的条件是否确实满足。如果该条件确实满足,即可确信程序行为没有错误,否则,条件并不满足,将引发异常错误。
unittest.TestCase 中常用的6个断言:
assertEqual(a,b) 核实 a==b
assertNotEqual(a,b) 核实 a!=b
assertTrue(x) 核实 x=True
assertFalse(x) 核实 x=False
assertIn(item,list) 核实 item in list
assertNotIn(item,list) 核实 item not in list
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 = """
6""" - 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"