2021 most complete Python interface test automation tutorial [learning materials attached]

Keywords: Python unit testing software testing API testing

[Abstract] interface definition: interface generally has two meanings. One is API (Application Programming Interface), which is a set of definitions, programs and protocols to realize the mutual communication between computer software through API interface. The other is interface, which is a specification of object-oriented languages such as java, c# etc. it can realize the function of multi inheritance. The interface in interface test refers to API. Why use the interface: if the company's product front-end development has not been completed

Article catalog

1, Interface definition
2, Basic process
3, Demand analysis
4, Use case design
5, Script development
6, Automated test resource sharing

1, Interface definition

Interface generally has two meanings. One is API (Application Program Interface), which is a set of definitions, programs and protocols. It realizes the mutual communication between computer software through API interface. The other is interface, which is a specification of object-oriented languages such as java, c# etc. it can realize the function of multi inheritance. The interface in interface test refers to API.

Why use interfaces:

If the company's product front-end development has not been completed, the interface has been developed. One day, the leader said, Xiao Wang, you test this login function. If you don't understand the interface, you will say to the leader that this function can't be tested. The page hasn't been developed. The leader will take you@ ¥@)¥!

Interface testing does not need to look at the front-end page. You can intervene in the testing work earlier to improve work efficiency.

According to the test pyramid, the lower the cost, the lower the level, and a bug at the bottom may cause multiple bugs at the upper level. Therefore, the lower the test level, the better the product quality can be guaranteed and the test cost can be saved. Unit testing is generally completed by development, so interface testing is very necessary for testing.

For automated testing, the UI is the most changeable, so the maintenance cost of UI automated testing is very high. The change of the interface is very small, so the interface automatic test is the most practical and cost-effective.

2, Basic process

The automatic test process of interface function is as follows: requirement analysis - > use case design - > script development - > test execution - > result analysis


2.1 example interface
Mobile phone number home
Interface address:   apis.juhe.cn/mobile/get
Return format:   json/xml
Request method:   get
Request example:   apis.juhe.cn/mobile/get?...

3, Demand analysis

Requirements analysis refers to requirements, design and other documents. On the basis of understanding the requirements, it is also necessary to understand the internal implementation logic, and can put forward the unreasonable or omission of requirements and design at this stage.
For example, in the mobile phone number home interface, enter the mobile phone numbers of different number segments to view the mobile phone number home and which operator the mobile phone number belongs to

4, Use case design

5, Script development

5.1 Module installation
 use pip Command to install:
pip install requests Copy code
5.2 Interface call
   use requests Library, we can easily write the above interface call methods (such as input) phone=Mobile phone number, example code is as follows):
   When we actually write automated test scripts, we need some encapsulation.
 #!/usr/bin/python3 import unittest import requests import json class Test_Moblie(unittest.TestCase):  # Encapsulating public data def common (self, phone): url =“ http://apis.juhe.cn/mobile/get " date = {     'key': "4391b7dd8213662798c3ac3da9f54ca8",     'phone': phone } self.response = requests.get(url, params=date) return self.response def test_ 1(self): self.common("1857110") print(self.response.text) def test_ 2(self): self.common("1868115") print(self.response.text) if __ name__ == '__ main__':  Unittest. Main() copy code
 \
   According to the test case design, we can write the automatic test script of each function in turn.
 5.3 Result verification
   When testing the interface manually, we need to judge whether the test passes through the results returned by the interface, and so does the automatic test.
   For this interface, enter the mobile phone, and we need to judge the returned result resultcode If it is equal to 200, you need to check whether the number of returned results is correct when paging results. The complete result verification code is as follows:
 #!/usr/bin/python3 import unittest import requests class Test_Moblie(unittest.TestCase):  # Encapsulate public data def common(self, phone): url = "http://Apis.juhe.cn/mobile/get "date = {key ':" 4391b7dd8213662798c3ac3da9f54ca8 ",'phone': Phone} self.response = requests.get (URL, params = date) return self.response def test_2 (self): self.common (" 1868115 ") print (self.response. Json()) dict_2 = self.response. Json() # the value of the printed province is: 200 resultcode = dict_2["resultcode "] #As an example of an expression error, change the comparison value to 200 and the correct value to 200. You can modify self.assertEqual(resultcode, "200", msg = 'failure reason:% s! =% s'% (resultcode, "200")) if _name _ = =' _ ': unittest. Main() copy the code
 \
 Operation results:
 

 5.4 Generate test report
   After the use case is executed, a report needs to be sent to the leader.
   So we use HTMLTestRunner Third party module plug-in generation html Format test report
 from unittest import TestSuite from unittest import TestLoader import requests import json import HTMLTestRunner import unittest class Test_Moblie(unittest.TestCase):  # Encapsulate public data def common(self, phone): url = "http://apis.juhe.cn/mobile/get" date = {     'key': "4391b7dd8213662798c3ac3da9f54ca8",     'phone': phone } self.response = requests.get(url, params=date) return self.response def test_1(self): "" "judge status code" "" self.common("1857110") print(self.response.json()) # return data as dict print(type(self.response.json())) dict_1 = self.response.json() # print value province value: Hubei province = dict_1["result"]["province"] self.assertEqual(province, "Hubei", msg = 'failure reason:% s! =% s'% (province, "Hubei")) def test_2(self): "" "judge provinces" "" self.common("1868115") print(self.response.json()) dict_2 = self.response.json() # printed value: Hubei resultcode = dict_2["resultcode"] # is an example of formula error. Change the comparison value to 201 and the correct value to 200. You can modify self.assertEqual(resultcode, "201", msg = 'failure reason:% s! =% s'% (resultcode, "200")) if__ name__ == '__ main__':  Report = "E: / report_path / result. HTML" file = open (report, "WB") # create test suite TestSuite = unittest. Testsuite() testload = unittest. Testloader() # the class name is passed in parentheses, and all use cases starting with test will be found automatically # use cases will be stored in the form of example table case = testload.loadtestsfromtestcase (test_moblie) testsuite.addtests (case) Run = htmltestrunner.htmltestrunner (stream = file, title = "interface automation test report", description = "use case execution result") run.run (TestSuite) file. Close() copy code
 5.5 Send mail Report
   After the test, we can use zmail Module provides methods to send html Format test report
   The basic process is to read the test report -> Add mail content and attachments -> Connect to the mail server -> Send mail -> Exit. The example code is as follows:
 #!/usr/bin/python3 import zmail def send_mail():  # Define mail mail = {"subject": "Interface test report",# Any fill 'content_text': 'Mobile phone number attribution_API Automated test report',# Any fill  # Multiple attachment usage list "attachments": "E:/report/result.html" }  # Custom server server = zmail.server("Sender email.com", "QQ The mailbox uses an authorization code", smtp_host="smtp.qq.com", smtp_port = 465)  # Send mail server.send_mail("recipient's QQ mailbox", mail) try: send_mail() except FileNotFoundError: print("file not found") else: print("sent successfully") copy code
 6. Result analysis
   After opening the test report generated after completion, you can see that there are two test cases executed in this test, one successful and one failed 

Finally, send the test report email. The screenshot is as follows:

6, Automated test resource sharing

Finally, I would like to thank everyone who carefully reads my article. Watching the rise and attention of fans all the way, reciprocity is always necessary. Although it is not very valuable, you can take it directly if you can use it:

These materials should be the most comprehensive and complete preparation warehouse for friends of advanced automation. This warehouse also accompanies tens of thousands of test engineers through the most difficult journey. I hope it can also help you!

In my QQ technology exchange group (technology exchange and resource sharing, advertising do not disturb)

You can take it away yourself, group number: 310357728, free information in the group is the essence of the author's more than 10 year test career. And the great gods of the same industry exchange technology together

If it's helpful to you, point a praise, collect a collection, and give the author an encouragement. It is also convenient for you to find it quickly next time.

Posted by daredevil88 on Thu, 28 Oct 2021 00:09:07 -0700