Still struggling with how to do interface automation testing? Teach you the complete Python interface automation test hand in hand! The whole network starts! Source code attached

catalogue

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 and c\. 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 tell 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. It can be involved in the testing work earlier to improve work efficiency.

According to the test pyramid, the lower the cost, the lower the level. 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 usually 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. However, the change of the interface is very small, so the interface automatic test is the most practical and cost-effective.

2. basic process

The interface function automation test process is as follows:
Requirements analysis - > use case design - > script development - > test execution - > result analysis

2.1 example interface

Mobile phone number home

Interface address: http://apis.juhe.cn/mobile/get
Return format: json/xml
Request method: get
Request example: http://apis.juhe.cn/mobile/get?phone= Mobile number &KEY= the KEY you applied for

3. demand analysis

Requirements analysis refers to documents such as requirements and design. On the basis of understanding the requirements, it is also necessary to understand the internal implementation logic, and at this stage, it is possible to put forward unreasonable or omitted requirements and design.

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 the pip command to install:
pip install requests

5.2 interface call

Using the requests library, we can easily write the above interface call methods (for example, enter phone= mobile number, and the example code is as follows):
When we actually write automated test scripts, we need to do some encapsulation.
 
#!/usr/bin/python3

import unittest
import requests
import json

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):
        self.common("1857110")
        print(self.response.text)

    def test_2(self):
        self.common("1868115")
        print(self.response.text)

if __name__ == '__main__':
    unittest.main() 
 
According to the test case design, we can write the automated test script for each function in turn.

5.3 result verification

When testing the interface manually, we need to judge whether the test has passed through the results returned by the interface, and so does the automated test.
For this interface, when inputting the mobile phone, we need to determine whether the returned resultcode is equal to 200. When paging the results, we need to verify whether the number of returned results is correct. 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()
        # Print value province value: 200
        resultcode = dict_2["resultcode"]
        # As an example of formula error, the comparison value is changed to 200, and the correct value is 200, which can be modified by yourself
        self.assertEqual(resultcode, "200", msg='Failure reason:%s != %s' % (resultcode, "200"))

if __name__ == '__main__':
    unittest.main()

Operation results:

5.4 generate test report

After the use case is executed, a report needs to be sent to the leader.
Then we use the HTMLTestRunner third-party module plug-in to generate html format test reports
 
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):
     """Judgment status code""" self.common(
"1857110") print(self.response.json()) # The returned data is 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):
     """Judging provinces""" self.common(
"1868115") print(self.response.json()) dict_2 = self.response.json() # Print value province value: Hubei resultcode = dict_2["resultcode"] # As an example of formula error, the comparison value is changed to 201, and the correct value is 200, which can be modified by yourself 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 testsuit = 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 are stored as example tables case = testload.loadTestsFromTestCase(Test_Moblie) testsuit.addTests(case) run = HTMLTestRunner.HTMLTestRunner(stream=file, title="Interface automation test report", description="Case execution results") run.run(testsuit) file.close()

5.5 sending email Report

After the test is completed, we can use the method provided by the zmail module to send the test report in html format

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 message
    mail = {"subject": "Interface test report",# Any fill
            'content_text': 'Mobile phone number home_API Automated test report',# Any fill
            # Multiple attachment usage lists
            "attachments": "E:/report/result.html"
            }
    # Custom server
    # If you don't know how to view the authorization code, please check this blog: https://www.cnblogs.com/zzpython/p/13095749.html
    server = zmail.server("Sender email.com",
                          "QQ E-mail uses authorization code",
                          smtp_host="smtp.qq.com",
                          smtp_port = 465)
    # Send mail
    server.send_mail("recipients QQ mailbox", mail)

try:
    send_mail()
except FileNotFoundError:
    print("no files found")
else:
    print("Sent successfully")

6. result analysis

Open 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, the test report email is sent. The screenshot is as follows:

 

 

If the article is helpful to you, please give me a like. Thank you for your support. Your like is the driving force for my continuous update.
For software testing, interface testing, automation testing, technical peers, continuous integration, interview experience exchange. If you are interested, you can go to 902061117. There will be irregular sharing of test data within the group.

Posted by daebat on Thu, 02 Jun 2022 01:16:10 +0530