Teach you complete Python interface automation-with source code

Preface


Interface definition:

Interface generally has two meanings, one is API (Application Program Interface), application programming interface, which is a set of definitions, procedures and protocols, through the API interface to achieve mutual communication between computer software. The other is Interface, which is a specification in object-oriented languages ​​such as java, c#, etc., which can implement multiple inheritance functions. The interface in the interface test refers to the API.

Why use interface:

If the company's product front-end development has not been completed, the interface has been developed. One day the leader said, Xiao Wang, if you test this login function, if you don't understand the interface, you will tell the leader that this function is untestable, and the page has not been developed. The leader will treat you! @¥@)¥!

Interface testing does not need to look at the front-end page, and can be involved in the testing work earlier to improve work efficiency.


According to the test pyramid, the lower the cost, the lower the cost. A bug in the bottom layer may cause multiple bugs in the upper layer. Therefore, the lower the test, the better the quality of the product can be guaranteed, and the more cost of testing can be saved. Unit testing is usually done by development, so for testing, interface testing is very necessary.

For automated testing, the UI has the greatest variability, so the maintenance cost of UI automated testing is high. The interface changes are very small, so the automatic interface test is the most practical and cost-saving.

2. Basic process

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

2.1 Example interface

Mobile phone number attribution
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 phone Number&key=The KEY you applied for

3. Demand analysis

Requirement analysis refers to documents such as requirements and design. On the basis of understanding requirements, it is necessary to know the internal implementation logic, and at this stage, requirements and design unreasonable or omissions can be proposed.

For example: mobile phone number attribution interface, enter the mobile phone number of different number ranges, check the mobile phone number attribution 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 calling methods (for example, enter phone=mobile phone number, the sample code is as follows):
when actually writing automated test scripts, we need to do some encapsulation.

#!/usr/bin/python3

import unittest
import requests
import json

class Test_Moblie(unittest.TestCase):

    # 封装公共的数据
    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() 
 

We follow the test case design and write automated test scripts for each function in turn.

5.3 Result verification

When manually testing the interface, we need to judge whether the test passed through the result returned by the interface, and the same is true for automated testing.
For this interface, enter the mobile phone, we need to determine whether the returned result resultcode is equal to 200. When the results are paged, we need to verify whether the number of returned results is correct, etc. The complete result verification code is as follows:

#!/usr/bin/python3

import unittest
import requests

class Test_Moblie(unittest.TestCase):

    # 封装公共的数据
    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()
        # 打印值省份值为:200
        resultcode = dict_2["resultcode"]
        # 为演式错误的示例,将对比值改为200,正确值为200,可自行修改
        self.assertEqual(resultcode, "200", msg='失败原因:%s != %s' % (resultcode, "200"))

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

operation result:

5.4 Generate test report

After the use case is executed, it needs to be reported to the leader.
Then we use HTMLTestRunner third-party module plug-in to generate 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):

    # 封装公共的数据
    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.json())
        # 返回数据为dict
        print(type(self.response.json()))
        dict_1 = self.response.json()
        # 打印值省份值为:湖北
        province = dict_1["result"]["province"]
        self.assertEqual(province, "湖北", msg='失败原因:%s != %s' % (province, "湖北"))

    def test_2(self):
     """判断省份"""
        self.common("1868115")
        print(self.response.json())
        dict_2 = self.response.json()
        # 打印值省份值为:湖北
        resultcode = dict_2["resultcode"]
        # 为演式错误的示例,将对比值改为201,正确值为200,可自行修改
        self.assertEqual(resultcode, "201", msg='失败原因:%s != %s' % (resultcode, "200"))

if __name__ == '__main__':

    report = "E:/report_path/result.html"
    file = open(report,"wb")
    # 创建测试套件
    testsuit = unittest.TestSuite()
    testload = unittest.TestLoader()
    # 括号内传入的是类名,会自动找到以test开头全部的用例
    # 用例以例表形式存储
    case = testload.loadTestsFromTestCase(Test_Moblie)
    testsuit.addTests(case)
    run = HTMLTestRunner.HTMLTestRunner(stream=file,
                                        title="接口自动化测试报告",
                                        description="用例执行结果")
    run.run(testsuit)
    file.close()

5.5 Send email report

After the test is completed, we can use the method provided by the zmail module to send a 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 sample code is as follows:

#!/usr/bin/python3

import zmail


def send_mail():
    # 定义邮件
    mail = {
    
    "subject": "接口测试报告",# 任一填写
            'content_text': '手机号归属地_API自动化测试报告',# 任一填写
            # 多个附件使用列表
            "attachments": "E:/report/result.html"
            }
    # 自定义服务器
    # 如果不知道如何查看授权码,请查看这一篇博客:https://www.cnblogs.com/zzpython/p/13095749.html
    server = zmail.server("发送人邮箱.com",
                          "QQ邮箱是用授权码",
                          smtp_host="smtp.qq.com",
                          smtp_port = 465)
    # 发送邮件
    server.send_mail("收件人QQ邮箱", mail)

try:
    send_mail()
except FileNotFoundError:
    print("未找到文件")
else:
    print("发送成功")

6. Result analysis

After opening the test report generated after the completion, it can be seen that a total of 2 test cases were executed in this test, one succeeded and one failed

The test report email is finally sent, the screenshot is as follows:

If the article is helpful to you, please reach out to make a fortune and give me a like. Thank you for your support. Your likes are my motivation for continuous updating.

If you want to exchange experience in software testing, interface testing, automated testing, technical peers, continuous integration, and interviews. If you are interested, you can go to 313782132. There will be occasional sharing of test data in the group.


Finally: benefits

In the technology industry, you must improve your technical skills and enrich your practical experience in automation projects. This will be very helpful for your career planning in the next few years and the depth of your testing technology.

In the interview season of the Golden 9th and the Silver 10th, the job-hopping season, organizing interview questions has become my habit for many years! The following is my collection and sorting in recent years, the whole is organized around [software testing], the main content includes: python automation test exclusive video, Python automation details, a full set of interview questions and other knowledge content.

For software testing friends, it should be the most comprehensive and complete interview preparation warehouse. In order to better organize each module, I also refer to many high-quality blog posts and projects on the Internet, and strive not to miss every knowledge point. Friends relied on these contents to review and got offers from big factories such as BATJ. This warehouse has also helped many learners of software testing, and I hope it can help you too!

May you and I meet and you will find something! Welcome to follow the WeChat public account: [Sad Spicy Article] Receive a 216-page software test engineer interview book for free. And the corresponding video learning tutorials are free to share!

Guess you like

Origin blog.csdn.net/weixin_50829653/article/details/112892706