python测试用例库使用
unittest库可以支持单元测试用例编写和验证。
基本使用方法
运行文件可以将文件中的用例全部执行一遍
import unittest
class TestBasicFunc(unittest.TestCase):
def test_basic_asert(self):
self.assertEqual(1, 1)
if __name__=="__main__":
unittest.main()
运行结果如下图:
基本断言用法
基本断言用法如下:
import unittest
class TestBasicFunc(unittest.TestCase):
def test_basic_asert(self):
self.assertEqual(1, 1)
self.assertNotEqual(1, 2)
self.assertAlmostEqual(3.01, 3.02, places=1)
self.assertNotAlmostEqual(3.1, 2.9, places=2)
self.assertTrue(3>2)
self.assertFalse(3<2)
self.assertIs("Hello", str("Hello"))
self.assertIn("s", "is a good")
python支持requests库发送网络请求
发送get请求,解析对应返回json文本
import requests
def try_request_get_test_case():
url = "http://127.0.0.1:8000/index/"
headers = {"Content-Type": "application/json"}
response = requests.get(url, headers=headers)
return_json = json.loads(response.text)
print(return_json)
return return_json
发送post请求
import requests
def try_request_post_test_case():
url = "http://127.0.0.1:8000/index/"
payload = {
"postWoman" : "localTest"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
return_json = json.loads(response.text)
print(return_json)
return return_json
django支持解析json格式body
解析json格式的body,需要用.body,而不是get函数
from django.shortcuts import render
from django.shortcuts import HttpResponse
import json
# Create your views here.
def index(request):
postWoman=""
if request.method == "POST":
print("index!")
body_json = json.loads(request.body)
postWoman = body_json["postWoman"]
print(postWoman)
data = {
'name':"hhhh",
'age':'15',
'item':"test",
"postWoman":postWoman
}
return HttpResponse(json.dumps(data));
整个测试用例demo
#!/usr/bin/env python
# coding: utf-8
import requests
import json
import unittest
def try_request_get_test_case():
url = "http://127.0.0.1:8000/index/"
headers = {"Content-Type": "application/json"}
response = requests.get(url, headers=headers)
return_json = json.loads(response.text)
print(return_json)
return return_json
def try_request_post_test_case():
url = "http://127.0.0.1:8000/index/"
payload = {
"postWoman" : "localTest"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
return_json = json.loads(response.text)
print(return_json)
return return_json
class TestBasicFunc(unittest.TestCase):
def test_basic_asert(self):
self.assertEqual(1, 1)
self.assertNotEqual(1, 2)
self.assertAlmostEqual(3.01, 3.02, places=1)
self.assertNotAlmostEqual(3.1, 2.9, places=2)
self.assertTrue(3>2)
self.assertFalse(3<2)
self.assertIs("Hello", str("Hello"))
self.assertIn("s", "is a good")
class TestRequestGet(unittest.TestCase):
def test_get_func(self):
return_json = try_request_get_test_case()
self.assertEqual(return_json["postWoman"], "")
def test_post_func(self):
return_json = try_request_post_test_case()
self.assertEqual(return_json["postWoman"], "localTest")
if __name__=="__main__":
unittest.main()