CSDN's latest and most complete python+pytest interface automation (12)-automated use case writing ideas (use pytest to write a test script)

After the previous study, we tried to use the pytest framework to write an interface automation test case to clarify the idea of ​​​​writing interface automation use cases.

When we search on Baidu天气查询, the results shown below will appear:

Next, we take the weather query interface as an example to write an interface test case script.

1. Clarify the test objects

To do interface testing for a certain function, first we need to determine which interface is called to implement this function. The specific information of this interface (such as function, protocol, URL, request method, request parameter description, response parameter description, etc.) can be viewed by The interface document provided by the development can also be obtained through packet capture (in the absence of interface document). Only after finding the corresponding interface, which is the test object, can we proceed to the next step purposefully.

1. There is obviously no interface document here that provides interface-related information. We don’t even know the request URL, so first capture the packet with Fiddler to obtain the interface information.

Through packet capture, we captured the information of this interface as follows:

请求url:https://weathernew.pae.baidu.com/weathernew/pc

Request method: GET

Request parameters:

2. After grabbing the above interface information, we first write a simple script to request the interface, as follows:

url = "https://weathernew.pae.baidu.com/weathernew/pc"
params = {
	"query": "浙江杭州天气",
	"srcid": 4982
}
res = requests.get(url=url, params=params)
print(res.status_code)
print(res.text)

Run the code, the interface debugging passes, and the results can be obtained, as follows:

3. Clarify requirements and determine use cases.

When we do automated testing for an interface, we need to first clarify the test points that need to be verified by the use case. Some interfaces require both forward verification and exception verification, while some interfaces may only require forward verification during automation without exception verification.

Let's analyze the weather query interface of the example. There are two main test points:

  • Forward request: Enter an existing city to find the weather for the corresponding city

  • Abnormal request: Enter a city that does not exist, and an error message appears.

2. Write test cases

When writing test cases, we need to encapsulate the code, which can be encapsulated into test classes/methods and test functions. There are requirements for the naming method of use case encapsulation in pytest. For details, please refer to my previous articlepytest test naming rules.

As for encapsulation into a class or a function, there are actually no specific requirements. Generally, 同一个场景 or 同一个测试点相关的接口 can be defined as a class.

At the same time, the use case also needs to set assertions to verify whether the returned content is the expected content. Test cases must make assertions, otherwise it is meaningless.

Construct request data

Forward request, the data is as follows:

params = {
	"query": "浙江杭州天气",
    "srcid": 4982
}

Abnormal request, the data is as follows:

params = {
	"query": "微信公众号:测试上分之路",
    "srcid": 4982
}

We have already obtained the result of the forward request when debugging the request for the interface above, as shown in the screenshot above.

Let's take a look at the results of the abnormal request to prepare for subsequent assertion settings. The results are as follows:

After sends an abnormal request, the returned code is also 200, and 暂未开通此城市查询 will appear in the result, and the window.tplData content in the forward request will not appear.

 Recommended tutorials related to automated testing:

The latest automated testing self-study tutorial in 2023 is the most detailed tutorial for newbies to get started in 26 days. Currently, more than 300 people have joined major companies by studying this tutorial! ! _bilibili_bilibili

2023 latest collection of Python automated test development framework [full stack/practical/tutorial] collection essence, annual salary after learning 40W+_bilibili_bilibili

Recommended tutorials related to test development

The best in the entire network in 2023, the Byte test and development boss will give you on-site teaching and teach you to become a test and development engineer with an annual salary of one million from scratch_bilibili_bilibili

postman/jmeter/fiddler test tool tutorial recommendation

The most detailed collection of practical tutorials on JMeter interface testing/interface automated testing projects. A set of tutorials for learning jmeter interface testing is enough! ! _bilibili_bilibili

To teach yourself how to capture packets with fiddler in 2023, please be sure to watch the most detailed video tutorial on the Internet [How to Learn to Capture Packets with Fiddler in 1 Day]! ! _bilibili_bilibili

In 2023, the whole network will be honored. The most detailed practical teaching of Postman interface testing at Station B can be learned by novices_bilibili_bilibili

Package test code

Here are two different test cases for the same interface. We directly encapsulate a test class specifically for testing the interface. The sample code is as follows:

class TestWeather:
    '''
    校验百度天气查询接口:https://weathernew.pae.baidu.com/weathernew/pc
    '''

    def test_get_weather_normal(self):
        '''正向校验-查询存在的城市的天气'''
        url = "https://weathernew.pae.baidu.com/weathernew/pc"
        params = {
            "query": "浙江杭州天气",
            "srcid": 4982
        }
        res = requests.get(url=url, params=params)


    def test_get_weather_error(self):
        '''异常校验-查询不存在的城市的天气'''
        url = "https://weathernew.pae.baidu.com/weathernew/pc"
        params = {
            "query": "微信公众号:测试上分之路",
            "srcid": 4982
        }
        res = requests.get(url=url, params=params)

Note that assertions have not been made in the code, so it cannot be considered a complete use case. Here I just put the assertion in the next step to illustrate the process, and then write the assertion after analysis.

Assertion settings

assertion, that is, checking whether the result is what we expect. For how to make assertions in pytest, please refer to the articlepytest-assertion.

When setting assertions, we need to first clarify which fields are checked. Generally speaking, the code of the interface response needs to be asserted. status_code == 200 means that the interface request is passed. Then assert other necessary fields to verify whether the interface function is implemented.

It can be seen from the above results that forward request can make the following assertion:

# 断言code是否等于200,存在则该断言通过
assert res.status_code == 200

# 断言结果中是否存在"window.tplData",存在则该断言通过
assert "window.tplData" in res.text

It can be seen from the above results that Exception request can make the following assertion:

# 断言code是否等于200,存在则该断言通过
assert res.status_code == 200

# 断言结果中是否存在"window.tplData",注意这里是不存在则该断言通过
assert "window.tplData" not in res.text

# 断言结果中是否存在"暂未开通此城市查询",存在则该断言通过
assert "暂未开通此城市查询" in res.text

3. Execute the script to obtain test results

When using the pytest framework to manage and execute use cases, you need to install pytest first and import it in the module. Students who are not sure can check my pytest series of articles, I won’t explain too much here.

The complete sample code is as follows:

# @time: 2022-03-20
# @author: 给你一页白纸
# 微信公众号:测试上分之路

import requests
import pytest


class TestWeather:
    '''
    校验百度天气查询接口:https://weathernew.pae.baidu.com/weathernew/pc
    '''

    def test_get_weather_normal(self):
        '''正向校验-查询存在的城市的天气'''
        url = "https://weathernew.pae.baidu.com/weathernew/pc"
        params = {
            "query": "浙江杭州天气",
            "srcid": 4982
        }
        res = requests.get(url=url, params=params)
        # print(res.status_code)
        # print(res.text)
        assert res.status_code == 200
        assert "window.tplData" in res.text


    def test_get_weather_error(self):
        '''异常校验-查询不存在的城市的天气'''
        url = "https://weathernew.pae.baidu.com/weathernew/pc"
        params = {
            "query": "微信公众号:测试上分之路",
            "srcid": 4982
        }
        res = requests.get(url=url, params=params)
        print(res.status_code)
        print(res.text)
        assert res.status_code == 200
        assert "window.tplData" not in res.text
        assert "暂未开通此城市查询" in res.text

        
if __name__ == '__main__':
    # 使用pytest执行用例
    pytest.main()

Of course, since the url is shared here, we'd better extract it instead of defining this variable for each test method, as shown in the following figure:

The execution results are as follows:

4. Summary

For a single interface automated test case, we can follow the above steps, that is, clarify the test object-->Write test case-->Write test script-->Execute the script and obtain the test results. Through these steps, we will have a basic idea for writing automated use cases (this is very important for the formation of our automated testing thinking), laying the foundation for our subsequent learning and practice.

In fact, when using a programming language to automate testing of a project, it is almost impossible to have only one test case. So when there are multiple test cases, how do you manage the use cases, execute the use cases, and obtain the test results? This is what a unit testing framework needs to solve.

  Summarize:

 Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned to practice. At this time, you can learn from some practical cases.

If it is helpful to you, please like and save it to give the author an encouragement. It also makes it easier for you to search quickly next time.

If you don’t understand, please consult the small card below. The blogger also hopes to learn and improve with like-minded testers.

At the appropriate age, choose the appropriate position and try to give full play to your own advantages.

My path to automated test development is inseparable from plans at each stage, because I like planning and summarizing.

Test development video tutorials and study notes collection portal! !

Guess you like

Origin blog.csdn.net/m0_70618214/article/details/134578416