Use Python+requests for interface automation testing

In the past two days, I have been looking for ways to directly use python to automate interfaces. I also searched some blog references on the Internet and tried it myself today.

1. Overall structure


The picture above shows the directory structure of the project. The following mainly introduces the role of each directory.

Common: Public methods: classes that mainly place public operations, such as database sqlhelper, file operation classes, etc.

Config: Public variables: mainly places public variables, such as ST, UAT, url address of the production environment, user name and password, database connection

Data: The data layer is somewhat similar to DAL in the three-tier architecture. It is the source of data. It is subdivided into json, xml, form and database according to the format of data storage.

Log: Log layer: stores logs to facilitate tracking and debugging

Page: Page layer: First divide the entire system into several subsystems, each subsystem contains several pages. This abstracts the page operated by the user into a page object, and the page operation into a method, so that the tester can pass different test cases for testing. If it is a service-oriented pure interface and there is no page, there is no need to divide it like this. , thus converting the interface test into a Python unit test.

Result: Stores the execution results of the unit test. You can also save the results of each execution to the database for management, and then do trend analysis of the test results. If the project is subsequently integrated into Jenkins, it is equivalent to Jenkins integrating python unit testing. In this case, this Layers may not be required.

Case: Test case layer. For the single method corresponding to the above Page, the test data and expected data are used to make assertion judgments. The test data and expected data used here can be placed in Excel later, and the tester only needs to fill in the test data.

Run: This is used to assemble a suite and then run the case.

At the same time, I have also prepared a software testing video tutorial for everyone (including interviews, interfaces, automation, performance testing, etc.), which is below. If you need it, you can watch it directly, or you can directly click on the small card at the end of the article to get the information document for free.

Where to watch software testing video tutorials:

Byte boss teaches you how to master automated testing (interface automation/APP automation/Web automation/performance testing) within 15 days, including practical project practice

2. Test

1. Install HTMLTestRunner

Download it and put it in the lib directory of the python installation directory

2. The business logic layer simulates some business processing here. When doing interface automation here, the requests library will be used to make requests.

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
 
def Add(name,pwd):
    session=requests.session()
    response=session.get('http://www.baidu.com')
    print(response.status_code)
    return response.status_code==200
 
def Edit(name,pwd):
    return {'name':name,'pwd':pwd}
 
def Delete(name,pwd):
    return {'name':name,'pwd':pwd}
 
def Search(name,pwd):
    return {'name':name,'pwd':pwd}

3. Case layer

The original plan was to add a suite layer. If it is a single interface, it is okay. If multiple interfaces are used for process testing, the order of the cases will not change when using the suite. If it is a process, it can also be written as a case, but the business logic layer needs to be called multiple times.

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import unittest
from Root.Page import Login
from Root.Page.UserManager import Index
import HTMLTestRunner
import time
class index(unittest.TestCase):
    def setUp(self):
        print('setUp')
    def tearDown(self):
        print('tearDown')
    def test_add(self):
       arr= Login.Login('admin', '123456')
       flag= Index.Add(arr[0], arr[1])
       self.assertTrue(flag)
       flag= Index.Add(arr[0], arr[1])
       self.assertTrue(flag==False)
    def test_edit(self):
       response= Login.Login('admin', '123456')
       dic= Index.Edit(response[0], response[1])
       self.assertNotEqual(dic,{'name':'123'})
    def test_delete(self):
       response= Login.Login('admin', '123456')
       dic= Index.Delete(response[0], response[1])
       self.assertNotEqual(dic,{'name':'123'})

4. Run

The main consideration here is that the entire system may be divided into different modules for operation, which will also be convenient for maintenance and can be executed by multiple executors. HTMLTestRunner is used here to generate reports.

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import unittest
from HTMLTestRunner import HTMLTestRunner
from Root.Test.Case.UserManager import Index
import HTMLTestRunner
import time
if __name__ == '__main__':
    # 1、构造用例集
    suite = unittest.TestSuite()
    # 2、执行顺序是安加载顺序:先执行test_sub,再执行test_add
    suite.addTest(Index.index("test_add"))
    suite.addTest(Index.index("test_edit"))
    suite.addTest(Index.index("test_delete"))
    suite.addTest(Index.index("test_edit"))
    suite.addTest(Index.index("test_edit"))
    filename = "../../../Result/{0}Report.html".format(time.strftime("%Y%m%d%H%M%S", time.localtime()) )  # 定义个报告存放路径,支持相对路径
    f = file(filename, 'wb')  # 结果写入HTML 文件
    runner = HTMLTestRunner.HTMLTestRunner(stream=f, title='测试报告', description='XXX系统接口自动化测试测试报告',verbosity=2)  # 使用HTMLTestRunner配置参数,输出报告路径、报告标题、描述
    runner.run(suite)

 

3. Test case parameterization

Each unit test above can only run the data of one test case, which is how to implement parameterization. In this way, you can run multiple unit tests by configuring the case data, which will be much more convenient. I found that the unit testing framework that comes with python does not support it. Nose and parameterized are used here.

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from nose.tools import assert_equal
from parameterized import parameterized
import HTMLTestRunner
import time
import unittest
import math
 
@parameterized([
    (2, 2, 4),
    (2, 3, 8),
    (1, 9, 1),
    (0, 9, 0),
])
def test_pow(base, exponent, expected):
    assert_equal(math.pow(base, exponent), expected)
 
class TestMathUnitTest(unittest.TestCase):
    @parameterized.expand([
        ("negative", -1.5, -2.0),
        ("integer", 1, 1.0),
        ("large fraction", 1.6, 1),
    ])
    def test_floor(self, name, input, expected):
        assert_equal(math.floor(input), expected)

Then cmd jumps to the directory of the python file and enters the command. It will run all the cases starting with test in the file, and then you can see the html file with the output result of one case.

nosetests testRuncase.py --with-html --html-report=nose_report2_test.html

4. Summary

PS: Here is a collection of self-study tutorials for software testing. It should be helpful to friends who are developing in the testing industry. If you need it, you can dd me. In addition to basic introductory resources, bloggers also collect a lot of advanced automation resources. From theory to practice, only by integrating knowledge and action can you truly master it. The full set of content has been packaged on the network disk, and the total content is close to 500 G.

☑ 240 episodes - a complete set of video courses from zero to mastery
☑ [Courseware + Source Code] - complete supporting tutorials
☑ 18 sets - source code of practical testing projects
☑ 37 sets - testing tool software package
☑ 268 - real interview questions
☑ 200 templates - Interview resume template, test plan template, software test report template, test analysis template, test plan template, performance test report, performance test report, performance test script case template (complete information)

These materials should be the most comprehensive and complete preparation warehouse for friends who do [software testing]. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you! Everything must be done early, especially in the technical industry, where technical skills must be improved.

 

Guess you like

Origin blog.csdn.net/huace3852/article/details/132854322