Application of unittest Framework in python
- 2021-12-04 10:19:59
- OfStack
1. Unittest is a test framework embedded in Python, which does not need special configuration
2. Write specifications
Import is required
import unittest
Test classes must inherit
unittest.TestCase
Test method begins with test_
Module and class names are not required
TestCase
Understanding as writing test cases
TestSuite
Understand as a collection of test cases
TestLoader
Test case loading understood as
TestRunner
Execute test cases and output reports
import unittest
from class_api_login_topup.demo import http_request
from class_api_login_topup.http_attr import Get_Attr # Reflected value Get cookies
# This is the file http_attr In Get_Attr Class
class Get_Attr:
cookies = None
class Login_Http(unittest.TestCase):
def __init__(self, methodName, url, data, method, expected):
super(Login_Http, self).__init__(methodName) # Hyperinheritance
self.url = url
self.data = data
self.expected = expected
self.method = method
def test_api(self): # Login normally
res = http_request().request(self.url, self.data, self.method, getattr(Get_Attr, 'cookies'))
if res.cookies:
setattr(Get_Attr, 'cookies', res.cookies)
try:
self.assertEqual(self.expected, res.json()['code'])
except AssertionError as e:
print("test_api's, error is {0}", format(e))
raise e
print(res.json())
if __name__ == '__main__':
unittest.main()
Execution 1:
import unittest
from class_demo_login_topup.http_tools import Login_Http
suite = unittest.TestSuite()
loader = unittest.TestLoader()
test_data = [{'url': 'http://test.lemonban.com/futureloan/mvc/api/member/login',
'data': {'mobilephone': 'xxxx', 'pwd': '123456'}, 'expected': '10001', 'method': 'get'},
{'url': 'http://test.lemonban.com/futureloan/mvc/api/member/login',
'data': {'mobilephone': 'xxxx', 'pwd': '12345678'}, 'expected': '20111', 'method': 'get'},
{'url': 'http://test.lemonban.com/futureloan/mvc/api/member/recharge',
'data': {'mobilephone': 'xxxx', 'amount': '1000'}, 'expected': '10001', 'method': 'post'},
{'url': 'http://test.lemonban.com/futureloan/mvc/api/member/recharge',
'data': {'mobilephone': 'xxxx', 'amount': '-100'}, 'expected': '20117', 'method': 'post'}]
# Traverse data and execute scripts addTest Single execution
for item in test_data:
suite.addTest(Login_Http('test_api', item['url'], item['data'], item['method'], item['expected']))
# Execute
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
# Running result
{'status': 1, 'code': '10001', 'data': None, 'msg': ' Login Successful '}
{'status': 0, 'code': '20111', 'data': None, 'msg': ' Wrong username or password '}
{'status': 1, 'code': '10001', 'data': {'id': 10011655, 'regname': ' Bee ', 'pwd': 'E10ADC3949BA59ABBE56E057F20F883E', 'mobilephone': 'xxxx', 'leaveamount': '150000.00', 'type': '1', 'regtime': '2021-07-14 14:54:08.0'}, 'msg': ' Successful recharge '}
{'status': 0, 'code': '20117', 'data': None, 'msg': ' Please enter the range in 0 To 50 A positive amount between ten thousand '}
Execution 2: Run the data of test_data in EXCEL.
import unittest
from class_demo_login_topup.http_tools import Login_Http
suite = unittest.TestSuite()
loader = unittest.TestLoader()
test_data = HttpExcel('test_api.xlsx', 'python').real_excel()
for item in test_data:
suite.addTest(Login_Http('test_api', item['url'], eval(item['data']), item['method'], str(item['expected'])))
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
Execution 3. Direct use of decorator ddt
import unittest
from class_api_login_topup.demo import http_request
from class_api_login_topup.http_attr import Get_Attr # Reflected value
from ddt import ddt, data, unpack
from class_demo_login_topup.http_excel import HttpExcel
test_data = HttpExcel('test_api.xlsx', 'python').real_excel()
@ddt
class Login_Http(unittest.TestCase):
@data(*test_data)
def test_api(self, item): # Login normally
res = http_request().request(item['url'], eval(item['data']), item['method'], getattr(Get_Attr, 'cookies'))
if res.cookies:
setattr(Get_Attr, 'cookies', res.cookies)
try:
self.assertEqual(str(item['expected']), res.json()['code'])
except AssertionError as e:
print("test_api's, error is {0}", format(e))
raise e
print(res.json())
Execute ddt Mode 1
import unittest
from class_demo_login_topup.http_tools import Login_Http
from class_demo_login_topup.http_excel import HttpExcel
suite = unittest.TestSuite()
loader = unittest.TestLoader()
from class_demo_login_topup import http_tools_1
suite.addTest(loader.loadTestsFromModule(http_tools_1)) # Execute the entire file
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
Execute ddt Mode 2
import unittest
from class_demo_login_topup.http_tools import Login_Http # No need ddt Method of
from class_demo_login_topup.http_excel import HttpExcel
suite = unittest.TestSuite()
loader = unittest.TestLoader()
from class_demo_login_topup.http_tools_1 import * # http_tools_1 The file is used ddt Method of
suite.addTest(loader.loadTestsFromTestCase(Login_Http)) # Execute http_tools_1 Under the file Login_Http Class, executed according to the class
with open('http_TestCase.txt', 'w+', encoding='UTF-8') as file:
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!