Python-based Interface Test Study Notes (first time), python Study Notes
I wrote my blog notes for the first time and talked about the recent automated testing of interfaces. After reading the relevant information online, I finally decided to use the python language to write the interface test, using the python third-party library requests. Although the python standard libraryUrllib2The module provides most of the HTTP functions you need. However, requests is easier to use. Decisive start learning.
Beginner, simple code
import requestsimport unittestclass apiTest(unittest.TestCase):def setUp(self):self.base_url='http://httpbin.org/get'self.list={'key1':'value1','key2':'valus2'}def tearDown(self): passdef test_api(self):response=requests.get(self.base_url,params=self.list)self.assertEqual(response.status_code,200) if __name__=='__main__':unittest.main()
First, import the corresponding requests module. It is the key for us to perform http request and other related functions. to install it, enter
$ pip install requests
Then import the unittest framework, which is a unit test framework of python, equivalent to the junit framework of java.
ApiTest inherits from unittest. TestCase and is a test case. The setUp () method is rewritten for Environment initialization. For example, you can establish a database connection in setUp () and perform some initialization to clear the data generated in the database in tearDown, close the connection. Variables, URLs, and submitted parameters are declared in the setUp () method. A method starting with test is also defined. Every method starting with test constructs a TestCase object for it. It is very easy to use Requests to send network Requests. For a get request: response = requests. get (self. base_url, params = self. list), two parameters in the get method are URL and transmitted parameters respectively. The request url is: http://httpbin.org/get? Key2 = value2 & key1 = value1. Add an assertion to determine whether the response is consistent with the expectation. here is whether the response status code is 200 or not.