unittest Framework analysis
unittest yes python The unit test framework of ,unittest Unit testing provides the ability to create test cases , Test suite and batch execution scheme , unittest In the installation pyhton I'll bring it myself , direct import unittest You can use .
open pycharm, introduce unittest package ,requests package
Then call unittest
class forTestTest(unittest.TestCase): # call unittest
Use unittest Medium setUp Method , This unittest We can write the preconditions of login in this, and we need to get cookie perhaps token And so on
class forTestTest(unittest.TestCase): # call unittest
def setUp(self) -> None: # precondition
# Login interface
re = requests.post(url='http://localhost:8888/login',data={'name': 'xiaohong', 'pwd': '456'})# Send interface request
print(re.text)# Print interface information
test = re.json()['data']['test'][0]['name']# Get the in the interface name value
print(test)# Print name value
global token# Set a global variable
token = re.json()['data']['token']# Assign values to global variables , The value is the response of the interface token Value
After adding a value condition , After the use case is executed, execute
def tearDown(self) -> None: # Postcondition
print(" end of execution ")# Print to mark the end of case execution
Write the specific interface to be executed , Write a query interface here , The login returned by calling the precondition token This value , Query interface access
!
def test_01(self):
# Query interface
res = requests.post('http://127.0.0.1:8888/user', data={'token': token})# Request query interface , Carry the login interface token value
a = res.text
print(a)# Print the results
If you don't want to write interface code here, you can use domestic interface testing tools apipost Directly generate
Run it and show you the results
Complete code
import unittest
import requests
class forTestTest(unittest.TestCase): # call unittest
def setUp(self) -> None: # precondition
# Login interface
re = requests.post(url='http://localhost:8888/login',data={'name': 'xiaohong', 'pwd': '456'})# Send interface request
print(re.text)# Print interface information
test = re.json()['data']['test'][0]['name']# Get the in the interface name value
print(test)# Print name value
global token# Set a global variable
token = re.json()['data']['token']# Assign values to global variables , The value is the response of the interface token Value
def tearDown(self) -> None: # Postcondition
print(" end of execution ")# Print to mark the end of case execution
def test_01(self):
# Query interface
res = requests.post('http://127.0.0.1:8888/user', data={'token': token})# Request query interface , Carry the login interface token value
a = res.text
print(a)# Print the results
if __name__ == '__main__':
unittest.main()